Skip to content

Instantly share code, notes, and snippets.

@phillipskevin
Last active August 15, 2018 19:28
Show Gist options
  • Save phillipskevin/a5892f9f1cf9a4d4ce936beb9080e615 to your computer and use it in GitHub Desktop.
Save phillipskevin/a5892f9f1cf9a4d4ce936beb9080e615 to your computer and use it in GitHub Desktop.
Forms with New Stache Syntax

Forms with CanJS 2.3 Stache Syntax

This gist shows examples of how to handle different types of form elements with the new stache binding syntax in CanJS 2.3.

var ViewModel = can.Map.extend({
define: {
options: {
value: [
'one',
'two',
'three'
]
},
selectedValues: {
Type: can.List,
Value: Array
}
},
selectedValuesContains: function(val) {
return this.attr('selectedValues').indexOf(val) >= 0;
},
toggleSelectedValue: function(val) {
var index = this.attr('selectedValues').indexOf(val);
if (index < 0) {
this.attr('selectedValues').push(val);
} else {
this.attr('selectedValues').splice(index, 1);
}
}
});
<form>
{{#each options}}
<input type="checkbox" {$value}="." id="{{option-%index}}" ($click)="toggleSelectedValue(%element.value)" {$checked}="selectedValuesContains(.)" >
<label for="{{option-%index}}">{{.}}</label>
{{/each}}
</form>
var ViewModel = can.Map.extend({
define: {
options: {
value: [
'one',
'two',
'three'
]
},
selectedValue: {
value: 'one',
set: function(val) {
console.log('selectedValue: ' + val);
return val;
}
}
},
setSelectedValue: function(val) {
this.attr('selectedValue', val);
}
});
<form>
{{#each options}}
<input type="radio" {$value}="." id="{{option-%index}}" ($click)="setSelectedValue(%element.value)" {{#is selectedValue .}}checked="checked"{{/is}} >
<label for="{{option-%index}}">{{.}}</label>
{{/each}}
</form>
var ViewModel = can.Map.extend({
define: {
options: {
value: [
'one',
'two',
'three'
]
},
selectedValue: {
set: function(val) {
console.log('selectedValue: ' + val);
return val;
}
}
}
});
<form>
<select {($value)}="selectedValue">
{{#each options}}
<option {$value}=".">{{.}}</option>
{{/each}}
</select>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment