Reputation: 817
I'm having an issue with backbone.js' models. I have a view that creates another view that has a new model created in it. But all the views seem to be referencing the same model. Heres some of the code.
menu: function(ev) {
var menu = new MenuView({});
console.log(menu);
ev = this.relativeEvData(ev);
menu.model.set('x',ev.relX);
menu.model.set('y',ev.relY);
this.$el.append(menu.render().el);
menu.addItem("cut","cut");
console.log('click');
}
define([
'jquery',
'underscore',
'backbone',
'text!templates/menuItem.html',
'models/menuModel'
], function($, _, Backbone, MenuItemTemplate, MenuModel){
var MenuView = Backbone.View.extend({
//... is a list tag.
tagName: "ul",
model: new MenuModel({}),
// Cache the template function for a single item.
template: null,
// The DOM events specific to an item.
events: {
},
initialize: function() {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
this.$el.addClass("contextMenu");
this.$el.css('display','block');
},
// Re-render the contents of the todo item.
render: function() {
console.log(this.model);
this.$el.html(this.model.get('items').join(''));
//update position
this.$el.css('top',this.model.get('y') + 'px');
this.$el.css('left',this.model.get('x') + 'px');
return this;
},
addItem: function(name,type) {
var items = this.model.get('items');
items.push('<li class="' + type + '"><a href="#' + type + '">' + name + '</a><li>');
this.model.set('items', items);
this.render();
},
// Remove the item, destroy the model.
clear: function() {
this.model.clear();
}
});
return MenuView;
});
define(['underscore', 'backbone'], function(_, Backbone) {
var MenuModel = Backbone.Model.extend({
// Default attributes for the todo.
defaults: function () {
return {
items:[],
x:0,
y:0
};
},
// nothing to initialize yet
initialize: function() {
},
// Remove this Todo from *localStorage*.
clear: function() {
this.destroy();
}});
return MenuModel;
});
All the MenuViews end up accessing the same model. What mistake am I making here?
Thank you for any help.
Upvotes: 0
Views: 219
Reputation: 13105
You are using the same model.
Skip the model: new MenuModel({}),
in your MenuView
.
In DesignView
instead of
var menu = new MenuView({});
you should create your model and pass it to the view, i.e.
var model = new MenuModel(),
menu = new MenuView({model: model});
Upvotes: 2