I am working with backbone and handlebars for a month and I have this problem.
I have this object that I get from my model:
Object {list: Object, permissions: Object}
list: Object
0: Object
id: "1"
name: "cms"
__proto__: Object
1: Object
2: Object
3: Object
permissions: Object
analytics: true
categories: false
cms: true
coupons: false
Now with handlebars I'm trying to find out how I can checked the box when the relative permission value is true like this:
{{#each list}}
<tr>
<th><input type="checkbox" id="{{id}}"
{{#each permission}}
{{#ifCond this {{name}} }}//that's where my current error is when I try to precompile this template,the syntax is wrong
checked
{{/ifCond}}
{{/each}}
/>{{name}}
</th>
</tr>
{{/each}}
ifCond is a function that I builded in handlebars.js:
Handlebars.registerHelper('ifCond', function(v1, v2, options) {
if(v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
});
Hope someone can help me out!!
Thank you!
This is how you would have written your template if there was no helper in the first place.
Start from this point
Without Helper
In the template you were trying to iterate over objects, which is not the right approach.
You should leave that to the template helper to take care of that passing the correct context.
---- This is again wrong ( something in these lines)
| compare="name"
{{#ifCond this {{name}} }}
^
^ ----- Context
|
Name of helper
under which it is
registered
When you pass a value to compare=name the value will be replaces by that key value of that object.
But remember that you are already inside each loop that iterates over list object.
So this will point to that object. So you need to go back to the parent object 1 step using ../ which will give you access to the permissions object.
{{#ifCond this compare=name }}
Will map to the arguments of the helper.
'ifCond', function(v1, v2, options) {
v1 will be this context
v2 will map to the handlebar options
options will be undefined as no 3rd argument was passed in the helper
So the template will be of this form
{{#ifCond this obj=../this compare=this.name}}
this - context of each (current object in loop)
obj= will be dumped into the options.hash object. It is the main object.
compare will be the name attribute inside this context
maps to
'ifCond', function (context, options)
So your template structure will look like below
Template
<script type="text/template" id="handlebar-template">
{{#each list}}
<tr>
<th>
<span>
<input type="checkbox" id="{{id}}"
{{#ifCond this obj=../this compare=this.name}}
checked
{{/ifCond}} />
</span>
<span class="name">{{name}}</span>
</th>
</tr>
{{/each}}
</script>
Helper
Handlebars.registerHelper('ifCond', function (context, options) {
var permissions = options.hash.obj.permissions,
name = options.hash.compare;
if (permissions[name]){
return options.fn(this);
}
return options.inverse(this);
});
Full Code
// The object in question
var obj = {
"list": [{
"id": 1,
"name": "cms"
}, {
"id": 2,
"name": "analytics"
}, {
"id": 3,
"name": "coupons"
}, {
"id": 4,
"name": "categories"
}],
"permissions": {
"analytics": true,
"categories": false,
"cms": true,
"coupons": false
}
};
// Model for the Object
var HandlebarModel = Backbone.Model.extend({});
var handlebarModel = new HandlebarModel(obj);
// View that will render the template inside the table
var HandlebarView = Backbone.View.extend({
el: $('#table'),
initialize: function () {
var source = $('#handlebar-template').html();
this.template = Handlebars.compile(source);
},
render: function () {
var $elem = $('tbody', this.$el);
$elem.empty();
$elem.append(this.template(this.model.toJSON()));
}
});
Handlebars.registerHelper('ifCond', function (context, options) {
console.log("this context " + this);
console.log("name -" + options.hash.compare);
console.log("Main Object - " + options.hash.obj);
var permissions = options.hash.obj.permissions,
name = options.hash.compare;
if (permissions[name]){
return options.fn(this);
}
return options.inverse(this);
});
var handlebarView = new HandlebarView({
model: handlebarModel
});
handlebarView.render();
Check Fiddle
Related
I do not have the best understanding of how ember.js works. I am currently working on updating an attribute called features (an array of strings) that each owner has using a multi select checkbox. So far everything seems to be working except for the updated features attribute is not saving. When I click the checkbox it updates the selected computed property in the multi-select-checkboxes component. I thought if I was passing model.owner.features as selected to the component it would directly update the model when the component changes.
(function() {
const { shroud } = Sw.Lib.Decorators;
Sw.FranchisorNewAnalyticsConnectionsUsersRoute = Ember.Route.extend({
currentFranchisorService: Ember.inject.service('currentFranchisor'),
#shroud
model({ account_id }) {
console.log("load model in route")
return Ember.RSVP.hash({
account: this.get('store').find('account', account_id),
owners: Sw.AccountOwner.fetch(account_id),
newAccountOwner: Sw.AccountOwner.NewAccountOwner.create({ accountID: account_id }),
});
},
actions: {
#shroud
accountOwnersChanged() {
this.refresh();
},
close() {
this.transitionTo('franchisor.newAnalytics.connections');
},
},
});
})();
users controller:
(function() {
const { shroud, on, observer } = Sw.Lib.Decorators;
Sw.FranchisorNewAnalyticsConnectionsUsersController = Ember.Controller.extend(Sw.FranchisorControllerMixin, {
isAddingUser: false,
adminOptions: [{
label: 'Employee Advocacy',
value: 'employee advocacy'
}, {
label: 'Second Feature',
value: 'other'
}, {
label: 'Can edit users?',
value: 'edit_users'
}],
});
})();
users.handlebars
{{#each model.owners as |owner|}}
<tr
<td>
{{owner.name}}
</td>
<td>
{{owner.email}}
</td>
<td>{{if owner.confirmedAt 'Yes' 'No'}}</td>
<td>
{{log 'owner.features' owner.features}}
{{multi-select-checkboxes
options=adminOptions
selected=owner.features
owner=owner
model=model
}}
</td>
<td>
<button class="btn light-red-button"
{{action "remove" owner}}>
Remove
</button>
</td>
</tr>
{{/each}}
multi-select-checkboxes.handlebar:
{{#each checkboxes as |checkbox|}}
<p>
<label>
{{input type='checkbox' checked=checkbox.isChecked}}
{{checkbox.label}}
</label>
</p>
{{/each}}
multi_select_checkboxes.jsx:
// Each available option becomes an instance of a "MultiSelectCheckbox" object.
var MultiSelectCheckbox = Ember.Object.extend({
label: 'label',
value: 'value',
isChecked: false,
changeValue: function () { },
onIsCheckedChanged: Ember.observer('isChecked', function () {
var fn = (this.get('isChecked') === true) ? 'pushObject' : 'removeObject';
this.get('changeValue').call(this, fn, this.get('value'));
})
});
Sw.MultiSelectCheckboxesComponent = Ember.Component.extend({
labelProperty: 'label',
valueProperty: 'value',
// The list of available options.
options: [],
// The collection of selected options. This should be a property on
// a model. It should be a simple array of strings.
selected: [],
owner: null,
model: null,
checkboxes: Ember.computed('options', function () {
console.log("CHECKBOXES", this.get('model'))
var _this = this;
var labelProperty = this.get('labelProperty');
var valueProperty = this.get('valueProperty');
var selected = this.get('selected');
var model = this.get('model');
return this.get('options').map(function (opt) {
var label = opt[labelProperty];
var value = opt[valueProperty];
var isChecked = selected.contains(value);
return MultiSelectCheckbox.create({
label: label,
value: value,
isChecked: isChecked,
model: model,
changeValue: function (fn, value, model) {
_this.get('selected')[fn](value);
console.log("model in middle", this.get('model'))
this.get('model').save();
}
});
});
}),
actions: {
amountChanged() {
const model = this.get(this, 'model');
this.sendAction('amountChanged', model);
}
}
});
Seems like you have a pretty decent understanding to me! I think your implementation is just missing a thing here or there and might be a tad more complex than it has to be.
Here's a Twiddle that does what you're asking for. I named the property on the model attrs to avoid possible confusion as attributes comes into play with some model methods such as rollbackAttributes() or changedAttributes().
Some things to note:
You don't need to specify a changeValue function when creating your list of checkbox objects. The onIsCheckedChanged observer should be responsible for updating the model's attribute. Just pass the model or its attribute you want to update (the array of strings) into each checkbox during the mapping of the options in the multi select checkbox:
return Checkbox.create({
label: option.label,
value: option.value,
attributes: this.get('owner.attrs') // this array will be updated by the Checkbox
});
If the model you retrieve doesn't have any data in this array, Ember Data will leave the attribute as undefined so doing an update directly on the array will cause an error (e.g., cannot read property 'pushObject' of undefined) so be sure the property is set to an array before this component lets a user update the value.
The observer will fire synchronously so it might be worthwhile to wrap it in a Ember.run.once() (not sure what else you will be doing with this component / model so I note this for completeness).
If you want to save the changes on the model automatically you'll need to call .save() on the model after making the update. In this case I would pass the model in to each checkbox and call save after making the change.
EDIT: I added this FIDDLE.
I'm a noobie to JSX and I'm trying to (correctly) build an image grid in React using a JSON file of images.
What is the best or "correct" approach for doing this?
My JSON file (updated per Nick's suggestion):
{
"images": [
{
"url": "./images/temp/playlist_tn_01.jpg",
"className": "playlist-tn"
},
{
"url": "./images/temp/playlist_tn_02.jpg",
"className": "playlist-tn"
},
{
"url": "./images/temp/playlist_tn_03.jpg",
"className": "playlist-tn"
}
]
}
My List module (copied from an example online):
var List = React.createClass({
render: function() {
return (
<ul>
{this.props.list.map(function(listValue){
return <li>{listValue}</li>;
})}
</ul>
)
}
});
module.exports = List;
My Updated list container component:
var Playlist = React.createClass({
render() {
let playlistImages = $.getJSON('images/temp/playlist_tn.json', images);
return (
<ReactCSSTransitionGroup transitionName="pagefade" transitionAppear={true} transitionAppearTimeout={500}>
<List list={playlistImages.images} />
</ReactCSSTransitionGroup>
)
}
})
module.exports = Playlist;
UPDATE FIDDLE
If you are rendering the component like this, e.g. passing the image node to the list property:
var mainComponent = React.createClass({
render() {
let jsonFileData = //ajax call to get file here
return (
<List list={jsonFileData.images} />
)
}
})
Then your jsx should read like this, you need to map the properties of the json onto an img element, and you need to use className instead of class as the property name :
var List = React.createClass({
render: function() {
return (
<ul>
{this.props.list.map(function(listValue){
return <li><img url={listValue.url} className={listValue.class} /></li>;
})}
</ul>
)
}
});
module.exports = List;
I would also recommend using arrow functions where possible in your maps, it makes things easier to read:
<ul>
{this.props.list.map( image =>
<li>
<img url={image.url} className={image.class} />
</li>
)}
</ul>
If you change your json class property to be called className and url to be src, you could use the spread operator to set all the props in one go too:
<img {...image} />
Working fiddle
Both functions here return 'undefined'. I can't figure out what's the problem.. It seems so straight-forward??
In the controller I set some properties to present the user with an empty textfield, to ensure they type in their own data.
Amber.ProductController = Ember.ObjectController.extend ({
quantity_property: "",
location_property: "",
employee_name_property: "",
//quantitySubtract: function() {
//return this.get('quantity') -= this.get('quantity_property');
//}.property('quantity', 'quantity_property')
quantitySubtract: Ember.computed('quantity', 'quantity_property', function() {
return this.get('quantity') - this.get('quantity_property');
});
});
Inn the route, both the employeeName and location is being set...
Amber.ProductsUpdateRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('product', params.product_id);
},
//This defines the actions that we want to expose to the template
actions: {
update: function() {
var product = this.get('currentModel');
var self = this; //ensures access to the transitionTo method inside the success (Promises) function
/* The first parameter to 'then' is the success handler where it transitions
to the list of products, and the second parameter is our failure handler:
A function that does nothing. */
product.set('employeeName', this.get('controller.employee_name_property'))
product.set('location', this.get('controller.location_property'))
product.set('quantity', this.get('controller.quantitySubtract()'))
product.save().then(
function() { self.transitionTo('products') },
function() { }
);
}
}
});
Nothing speciel in the handlebar
<h1>Produkt Forbrug</h1>
<form {{action "update" on="submit"}}>
...
<div>
<label>
Antal<br>
{{input type="text" value=quantity_property}}
</label>
{{#each error in errors.quantity}}
<p class="error">{{error.message}}</p>
{{/each}}
</div>
<button type="update">Save</button>
</form>
get rid of the ()
product.set('quantity', this.get('controller.quantitySubtract'))
And this way was fine:
quantitySubtract: function() {
return this.get('quantity') - this.get('quantity_property');
}.property('quantity', 'quantity_property')
Update:
Seeing your route, that controller wouldn't be applied to that route, it is just using a generic Ember.ObjectController.
Amber.ProductController would go to the Amber.ProductRoute
Amber.ProductUpdateController would go to the Amber.ProductUpdateRoute
If you want to reuse the controller for both routes just extend the product controller like so.
Amber.ProductController = Ember.ObjectController.extend ({
quantity_property: "",
location_property: "",
employee_name_property: "",
quantitySubtract: function() {
return this.get('quantity') - this.get('quantity_property');
}.property('quantity', 'quantity_property')
});
Amber.ProductUpdateController = Amber.ProductController.extend();
I ended up skipping the function and instead do this:
product.set('quantity',
this.get('controller.quantity') - this.get('controller.quantity_property'))
I still dont understand why I could not use that function.. I also tried to rename the controller.. but that was not the issue.. as mentioned before the other two values to fetches to the controller...
Anyways, thanks for trying to help me!
Against my controller, I have an item with an array of items which I want to display a list of and have an action to remove an item.
Have taken most of the code from a similar question item-specific actions in ember.js collection views. Majority of this works, the address display works and the items render, however the action does not seem to have the correct context and therefore does not perform the remove action.
Controller:
App.EditAddressesController = Em.ArrayController.extend({
temporaryUser: {
firstName: 'Ben',
lastName: 'MacGowan',
addresses: [{
number: '24',
city: 'London'
etc...
}, {
number: '23',
city: 'London'
etc...
}]
}
});
The temporaryUser is an EmberObject (based off a User model), and each item within the addresses array is another EmberObject (based off an Address model) - this has just been simplified for purposes of displaying code.
Parent view:
{{#each address in temporaryUser.addresses}}
{{#view App.AddressView addressBinding="this"}}
{{{address.display}}}
<a {{action deleteAddress target="view"}} class="delete">Delete</a>
{{/view}}
{{/each}}
App.AddressView:
App.AddressView = Ember.View.extend({
tagName: 'li',
address: null,
deleteAddress: function() {
var address = this.get('address'),
controller = this.get('controller'),
currentAddresses = controller.get('temporaryUser.addresses');
if(currentAddresses.length > 1) {
$.each(currentAddresses, function(i) {
if(currentAddresses[i] == address) {
currentAddresses.splice(i, 1);
}
});
}
else {
//Throw error saying user must have at least 1 address
}
}
});
Found out it was an issue with my each:
{{#each address in temporaryUser.addresses}}
should have been:
{{#each temporaryUser.addresses}}
And my AddressView should use removeObject (like the original code sample)
App.AddressView = Ember.View.extend({
tagName: 'li',
address: null,
deleteAddress: function() {
var address = this.get('address'),
controller = this.get('controller'),
currentAddresses = controller.get('temporaryUser.addresses');
if(currentAddresses.length > 1) {
currentAddresses.removeObject(address);
}
else {
//Throw error saying user must have at least 1 address
}
}
});
I think your code could become more readable if you approach it that way:
1- Modify your action helper to pass the address with it as context. I modified your Handlebars a bit to reflect the way i am approaching stuff like this and works for me. I think this is the "Ember way" of doing this kind of stuff, since a the properties in a template are always a lookup against the context property of the corresponding view:
{{#each address in temporaryUser.addresses}}
{{#view App.AddressView contextBinding="address"}}
{{{display}}}
<!-- this now refers to the context of your view which should be the address -->
<a {{action deleteAddress target="view" this}} class="delete">Delete</a>
{{/view}}
{{/each}}
2 - Modify the handler in your view to accept the address as a parameter:
App.AddressView = Ember.View.extend({
tagName: 'li',
address: null,
deleteAddress: function(address) {
var controller = this.get('controller'),
currentAddresses = controller.get('temporaryUser.addresses');
if(currentAddresses.length > 1) {
currentAddresses.removeObject(address);
}
else {
//Throw error saying user must have at least 1 address
}
}
});
I can not make the following code work in my test app:
this.propertyWillChange('tableContent');
this.get('tableContent').sort(function (a, b) {
var nameA = a.artikel_name,
nameB = b.artikel_name;
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0 //default return value (no sorting)
});
this.propertyDidChange('tableContent');
The data gets sorted, but the dom is not updated.
The template looks like this:
<tbody>
{{#each NewApp.router.gridController.tableContent}}
{{#view NewApp.TableRow rowBinding="this"}}
<td style="width: 100px">{{view.row.product_no}}</td>
<td align="right" style="width: 100px">{{view.row.price}}</td>
<td>{{view.row.artikel_name}}</td>
{{/view}}
{{/each}}
</tbody>
I tried to reproduce this problem with a short jsfiddle snippet. But there it works. The only difference is, that I fetch the data using an ajax call (and some additional router setup).
selectionChanged: function () {
var that = this;
if (this.selection) {
$.getJSON("api/v1/lists/" + this.selection.id + "/prices", function (content) {
that.set('tableContent', content);
});
}
}.observes('selection')
The same code works if i copy the array and reassign the copied array.
Did you try to use the built-in SortableMixin ? If not, is this good for you ?
JavaScript:
App = Ember.Application.create();
App.activities = Ember.ArrayController.create({
content: [{name: 'sleeping'}, {name: 'eating pizza'},
{name: 'programming'}, {name: 'looking at lolcats'}],
sortProperties: ['name']
});
App.ActivityView = Ember.View.extend({
tagName: "li",
template: Ember.Handlebars.compile("{{content}}")
});
App.SortButton = Ember.View.extend({
tagName: "button",
template: Ember.Handlebars.compile("Sort"),
click: function() {
App.activities.toggleProperty('sortAscending');
}
});
jsfiddle: http://jsfiddle.net/Sly7/cd24n/#base