Can you bind a simple javascript array to your ember.js template? - javascript

I'm using ember.js RC1 + ember-data rev 11 (but I also need some plain ajax for configuration like models). I want to loop over a simple objects list and display the records (note -here I create just a basic array)
The content I have bound has the following custom find method defined
App.Foo = DS.Model.extend({
name: DS.attr('string')
}).reopenClass({
records: [],
all: function() {
return this.records;
},
find: function() {
var self = this;
$.getJSON('/api/foo/', function(response) {
response.forEach(function(data) {
//say I want to kill everything in the array here for some strange reason...
self.records = [];
//the template still shows the record ... not an empty list ?
}, this);
});
return this.records;
}
});
My other model uses this directly
App.Related = DS.Model.extend({
listings: function() {
return App.Foo.find();
}.property()
});
Now inside my template
{{#each foo in related.listings}}
{{foo.name}}<br />
{{/each}}
The list loads up with whatever I put in the array by default (say I add a simple object using createRecord like so)
add: function(record) {
this.records.addObject(App.Foo.createRecord(record));
},
and when the template is rendered I see anything listed here... but as I put in the comments above, if I decide to remove records or null out the list that is bound it doesn't seem to reflect this in any way.
Is it possible to bind a simple array as I have and yet remove items from it using something basic such as splice? or even a drastic self.records = []; ?
self.records.splice(i, 1);
Even when I query the client manually after the splice or empty work it returns 0
console.log(App.Foo.all().get('length'));
Initially I see records, but then I see they are gone (yet the html doesn't change)

I understood your question this way, that the following remark is the point your are struggling with:
response.forEach(function(data) {
//say I want to kill everything in the array here for some strange reason...
self.records = [];
//the template still shows the record ... not an empty list ?
}, this);
You are wondering, why your template is showing no empty list? It's because you did not tell Ember when to update the template. You can tell Ember this way:
App.Related = DS.Model.extend({
listings: function() {
return App.Foo.find();
}.property("App.Foo.records.#each")
});
Now Ember knows, whenever something is added or removed from your array, it should update the listings property of your model. And therefore it knows that your view needs rerendering.
One additional remark to the orignal question regarding "simple javascript arrays". When you use Ember, you actually do not instantiate simple js arrays. When you declare:
var a = []; // is the same as -> var a = Ember.A();
Ember does some magic and wraps in an enhanced ember version of an array (Ember.NativeArray), which enables you to use such property dependency declarations mentioned above. This enables Ember to use ArrayObservers on those arrays, although they may feel like a plain JS Array.

You need to use the set method when you modify properties and get when you return them, or else Ember won't be able to do its magic and update the template.
In your case, there is an additional problem, which is that in find(), you return a reference to records before your asynchronous getJSON call replaces it with a new empty array. The calling method will never see the new array of records. You probably want to use clear() instead.
Your model should look something like this:
App.Foo = DS.Model.extend({
name: DS.attr('string')
}).reopenClass({
records: [],
all: function() {
// can't use 'this.get(...)' within a class method
return Ember.get(this, 'records');
},
findAll: function() {
var records = Ember.get(this, 'records');
$.getJSON('/api/foo/', function(response) {
records.clear();
// in this case my json has a 'foos' root
response.foos.forEach(function(json) {
this.add(json);
}, this);
}, this);
// this gets updated asynchronously
return records;
},
add: function(json) {
// in order to access the store within a
// class method, I cached it at App.store
var store = App.get('store');
store.load(App.Foo, json);
var records = Ember.get(this, 'records');
records.addObject(App.Foo.find(json.id));
}
});
Note that the addObject() method respects observers, so the template updates as expected. removeObject() is the corresponding binding-aware method to remove an element.
Here's a working jsfiddle.

Related

serializeData function vs Marionette.renderer for custom data

I've noticed Marionette is very un-opinionated as far things go for the freedom they give you to choose a method to render data. It seems like there are a lot of ways to initially render a template with custom data
Returning a template with data:
template: function () {
var myTemplate = $('.someTemplate')
return _.template(myTemplate.html())({some: data});
}
Very similarly:
render: function () {
var template = this.getTemplate();
var html = Marionette.Renderer.render(template, {
model: this.model.toJSON(),
customData: this.customData
});
this.$el.html(html);
}
Serialize data:
serializeData : function () {
var customData = {some: 'data'};
var model = this.model.toJSON()
return _.extend(customData, model);
}
I've seen a lot of people in different code use variations of the first and the second. I personally prefer using serializeData but am curious: is there an advantage or use case where it would be appropriate to use the first two methods instead of serializeData?
The first case is not efficient - you are recompiling the template every time you want to render.
Anyway, your use case is exactly why Marionette has templateHelpers. Its the most concise way to provide extra data to the template while also passing serialized model.
So you would write:
templateHelpers : function () {
return {some: 'data'};
}
Or if its just static stuff:
templateHelpers: {some: 'data'}
More examples on how to use it here.
I think it's all about exploring natural behaviour of these things. Backbone View render is empty function by default. Marionette ItemView render extends Backbone's with this code.
It takes template by getTemplate method, by default it gives what is stored in template option. You can override getTemplate if you want to choose between several templates.
Then it collects data needed to be rendered by runing serializeData and extending it with templateHelpers. First one by default returns your model or collection toJSON method result, there you can prepare your data some way on every render. Second one is for helpers that will be calculated (if they are functions) if needed in template.
Template and data then go to Marionette.Renderer where just return template(data) by default happens. And then result can be attached to view's element.

Backbone.js removing the model

I have been trying for hours now, without luck. If you could see on the image, I have mildly complex model. Image is taken from Chrome in debug.
I need to delete a model from collection, also I need to be able to change the URL where the backbone will shoot its ajax for delete. So in essence, this is my model structure:
attributes:
favorites {
bookmarkedArticles: [{id: 123123},{id: ...}],
bookedmarkedSearches: [{}],
dispatchesMailds: []
}
How can I delete model in bookmarkedArticles with id of 123123?
I have tried this:
var model = new metaModel(
{
favourites: {
bookmarkedArticles: {
id: "123123"
}
}
}
);
model.destroy();
also this
aamodel.headerData.collection.remove(model);
No success at all.
The information provided is not giving a lot of details, but I will try to answer considering two scenarios:
Option A:
You are trying to delete a model in the collection that has bookmarkedArticle.id="123123". if that is the case and considering the bookmarkedArticles it is just an Array of objects, I would suggest to filter the Collection using the underscore method filter and then delete the models returned by the filter.
var id = 123123;
var modelsToDelete = aamodel.headerData.collection.filter(function(model){
// find in the bookmarked articles
return _.find(model.get('bookmarkedArticles'), function(ba){
return (ba.id === id);
});
});
_.each(modelsToDelete, function(model){
model.destroy();
});
Option 2: If you want to remove the bookmarked article '123123' associated to your main model using just the 'destroy' method, firstable you have to convert 'bookmarkedArticles' to a Backbone.Collection as it is just an Array of Objects, there are some utilities for Backbone that allows you to do this easily:
https://github.com/blittle/backbone-nested-models
But by default this is not possible, then, If you want to remove the 'bookmarkedArticle' you can create the Backbone.Model and then use the method destroy. Example:
var BookmarkedArticle = Backbone.Model.extend({
url: function(){
return '/bookmarkArticle/' + this.id;
}
});
new BookmarkedArticle({"id": "123123","master": "5",...}).destroy();
Hope this information is useful and provide some guidance to solve your problem.

EmberJS dynamic observers at run-time?

Given the following models:
(note: these are simplified for illustration purposes)
App.CustomerOrder = DS.Model.extend({
deliveries: DS.hasMany('delivery'),
total: DS.attr('number')
});
App.Delivery = DS.Model.extend({
orderlines: DS.hasMany('orderline')
});
App.OrderLine = DS.Model.extend({
productid: DS.attr('string'),
qtyordered: DS.attr('number')
});
When the app first loads I'm querying an API that sends me information about which dependencies should trigger an update. So for example it'll send me something like:
CustomerOrder: ["deliveries", "deliveries.orderlines", "deliveries.orderlines.qtyordered"...]
..means, if deliveries are added/deleted from a customerorder or if lines are added/deleted from a delivery attached to a customer order or if the qtyordered on an orderline on a delivery attached to a customer order, then what the API expects is for me to serialize CustomerOrder (along with the entire chain of relationships) and sent to an 'update' service (i.e. server/customerorder/updates type thing) that will run various routines and fill-in pieces of data and send the entire chain of objects back.
For illustration purposes I've put a simple example on here of an ordertotal (I realize this is easily calculated client-side but there's a bunch of other stuff that would be duplication of code from the server). So, if the qtyordered on an orderline changes, I need to send the customerorder instance to the server, where it will update my total field.
One of the challenges is that I can't hard code that dependency list by setting up observer functions with .observes() type stuff, it has to be done dynamically after that dependency data is loaded (presumably using addObserver). The other is that observers wont dig multiple layers deep like that.
I've tried using a mix-in to the models that overrides the init function and does exactly that.
clientchangeset: DS.attr('raw'),
init: function() {
this._super.apply(this, arguments);
var className = this.auth.camelizedModelString(this.constructor.toString());
var watchlist = this.auth.dependencies[className] || null;
var self = this;
watchlist.forEach(function(watch) {
if(watch.hasOwnProperty('attributeName') && watch.hasOwnProperty('collectionFlag')) {
// {attributeName: attributeName, collectionFlag: collectionFlag}
if(watch['collectionFlag']) {
console.log(className+'.addObserver('+watch['attributeName']+'.#each.clientchangeset)');
self.addObserver(watch['attributeName']+'.#each.clientchangeset', null, 'updateChangelist');
} else {
console.log(className+'.addObserver('+watch['attributeName']+')');
self.addObserver(watch['attributeName'], null, 'updateChangelist');
}
}
});
},
This appears to work, but only one layer deep. For completeness, heres the updateChangelist function:
updateChangelist: function(src, field, value) { //jshint ignore:line
if(this.get('pauseUpdates')) {
return;
}
var className = this.auth.camelizedModelString(this.constructor.toString());
var oldclientchangeset = this.get('clientchangeset') || [];
console.log('Before: '+className+'.[clientchangeset]= '+oldclientchangeset);
oldclientchangeset.pushObject(field);
this.set('clientchangeset', oldclientchangeset);
console.log('After: '+className+'.[clientchangeset]= '+oldclientchangeset);
}
So in general the way I got this to work was to create the observers as indicated, but the handlers simply update a property called '_needsUpdate' on each level of the relationships whenever they are triggered. '_needsUpdate' is just a date so when triggered I do:
this.set('_needsUpdate', +new Date());
Then when setting up observers at each level for that level's children, I just set up a single observer to look at child.#each._needsUpdate.

Backbone Model: Keep Collection when saving

I have a simple Backbone model that looks like this:
(function () {
App.Company = Backbone.Model.extend({
defaults: {},
urlRoot: "/Contacts/Companies",
initialize: function () {
var contactPersons = this.get("ContactPersons") || [];
this.set("ContactPersons", new App.ContactPersonCollection(contactPersons));
}
});
})();
Whenever I save the model to the server, the ContactPersons collection is reset to an Array.
Is it really necessary for me to manually turn it into a collection, after a model is saved?
UPDATE: This works as intended -- See answer for better approach (IMHO)
(function () {
App.Company = Backbone.Model.extend({
defaults: {},
urlRoot: "/Contacts/Companies",
initialize: function () {
var contactPersons = this.get("ContactPersons") || [];
if (_.isArray(contactPersons)) {
this.set("ContactPersons", new App.ContactPersonCollection(contactPersons));
}
},
parse: function (response) {
if (response.ContactPersons && _.isArray(response.ContactPersons)) {
response.ContactPersons = new App.ContactPersonCollection(response.ContactPersons);
}
return response;
}
});
})();
When you send data back from the server, how are you handling the response? For example if you just send back a [{},{},{}] I don't think Backbone automatically knows to treat that as a collection. Thus, it sets the ContactPersons attribute as what it gets, your vanilla array.
What you can do, is override your set function inside your model which will take the array of objects passed in and write to the collection as proper. See this example:
set: function(attributes, options) {
if (_.has(attributes, 'ContactPersons') && this.get("ContactPersons")) {
this.get('ContactPersons').reset(attributes.ContactPersons);
delete attributes.ContactPersons;
}
return Backbone.Model.prototype.set.call(this, attributes, options);
}
So basically as long as your server response is properly namespaced (response.ContactPersons) then after parsing it will pass your response to the set function. The collection data is treated specially as a collection. Here, I'm just reseting the collection that already exists with the new data. All your other model attributes should continue to be passed on to the original set().
UPDATE - Growing doubt about own answer
I haven't been able to get this question/answer out of my mind. It certainly works, but I'm becoming unconvinced that using a modified set() vs. just doing things in parse() is any better. If someone has some comments on the difference between using a modified set() vs. parse() with nested models, I'd really welcome the input.

how to render a collection using backbone?

I have this backbone that is working fine, i just want to render the collection is been fetched!
code:
var SearchView = Backbone.View.extend({
events: {
"keyup": "handleChange"
},
initialize: function(){
this.collection.bind("reset", this.updateView, this);
},
render: function(){
// this is where i need help
this.$el.next('#suggestions').append(// iterate over this.collection and apppend here) //
},
handleChange: function(){
var term = this.$el.val();
this.collection.search(term);
},
updateView: function() {
this.render();
}
});
I just want to iterate over this.collection and display the "text" attribute thats inside each collection and append it to the ('#suggestions') el. thanks
Focusing on your reset, render over collections issue, this is how I would do it. This way assumes that when you create your view, the $el is already present and you're passing it in through the View constructor so it's ready to go.
var SearchView = Backbone.View.extend({
template: _.template('<span><%= term %></span>');
initialize: function(){
this.collection.bind("reset", this.render, this);
},
render: function(){
this.addAllTerms();
return this;
},
addAllTerms: function() {
var self = this;
this.collection.each(function(model) {
self.addTerm(model);
});
},
addTerm: function(someModel) {
this.$el.next('#suggestions').append(this.template(someModel.toJSON()));
}
});
It's a bit different from your approach in a few ways. First, we utilize Underscore's template function. This could be anything from span to li to div whatever. We use the <%= %> to indicate that we're going to interpolate some value (which will come from our model.term attribute).
Instead of going to the handler then render, I just bind the collection to render.
The render() assumes we're always going to refresh the whole thing, build from scratch. addAllTerms() simply cycles through the collection. You can use forEach() or just each() which is the same thing except forEach() is 3 characters too long for my lazy bum. ;-)
Finally, the addTerm() function takes a model and uses it for the value that it will append to the #suggestions. Basically, we're saying "append the template with interpolated value". We defined the template function up above as this View object property to clearly separate the template from data. Although you could have skipped this part and just append('<span>' + someModel.get('term') + '</span>') or what not. The _.template() uses our template, and also takes any sort of object with the property that lines up with the one in our template. In this case, 'term'.
It's just a different way to do what you're doing. I think this code is a little more manageable. For example, maybe you want to add a new term without refreshing the whole collection. The addTerm() function can stand on its own.
EDIT:
Not that important but something I utilize with templates that I found useful and I didn't see it when I first started out. When you're passing the model.toJSON() into the template function, we're essentially passing all the model attributes in. So if the model is like this:
defaults: {
term: 'someTerm',
timestamp: '12345'
}
In our previous example, the attribute timestamp is also passed in. It isn't used, only <%= term %> is used. But we could easily interpolate it as well by adding it to the template. What I want to get at is that you don't have to limit yourself to data from one model. A complex template might have data from several models.
I don't know if it's the best way, but what I do is have something like this:
makeHash: function() {
var hash = {};
hash.term = this.model.get('term');
hash.category = anotherModel.get('category');
var date = new Date();
hash.dateAccessed = date.getTime();
return hash;
}
So you can easily build your own custom hash to throw into a template, aggregating all the data you want to interpolate into a single object to be passed into a template.
// Instead of .toJSON() we just pass in the `makeHash()` function that returns
// a customized data object
this.$el.next('#suggestions').append(this.template(this.makeHash()));
You can also easily pass in whole objects.
makeHash: function() {
var hash = {};
hash.term = this.model.get('term');
var animal = {
name: 'aardvark',
numLegs: 4
};
hash.animal = animal;
return hash;
}
And pass this into our template that looks like this:
template: _.template('<span><%= term %></span>
<span><%= animal.name %></span>
<span><%= animal.numLegs %></span>')
I'm not sure if this is the best way but it helped me understand exactly what data is going into my templates. Maybe obvious but it wasn't for me when I was starting out.
I found the solution to the problem, im gonna put it here for people that might want to know:
render: function(){
this.collection.forEach(function(item){
alert(item.get("text"));
});
}

Categories