gpt4 book ai didi

javascript - 随时将 Active 属性仅设置为 Backbone Collection 中的 1 个模型

转载 作者:行者123 更新时间:2023-11-28 13:27:24 25 4
gpt4 key购买 nike

我有一组 Backbone 模型。我想将模型属性设置为“事件”,但确保一次只能有 1 个模型处于事件状态。我无法让它发挥作用,正在寻求一些指导。

这是我的代码的一个 fiddle :http://jsfiddle.net/doen1mm9/

这是我的 JavaScript 和模板。

JS:

var data = [
{
"color": "blue",
"name": "Johnny"
},
{
"color": "green",
"name": "Melissa"
},
{
"color": "yellow",
"name": "Bill"
}
];

var TheModel = Backbone.Model.extend({
});

var TheCollection = Backbone.Collection.extend({
model: TheModel,

initialize: function() {
this.on('change:isActive', this.ensureSingleActive, this);
},

ensureSingleActive: function(current) {
var previous = this.findWhere({isActive: true});

if (previous !== undefined) {
previous.set('isActive', false);
}

current.set('isActive', true);
}
});

var ListView = Backbone.View.extend({
el: '.js-container',

tagName: 'ul',

render: function() {
this.collection.each(function(item) {
var listItemView = new ListItemView({model: item});
this.$el.append(listItemView.el);
}, this);
}
});

var ListItemView = Backbone.View.extend({

initialize: function() {
this.listenTo(this.model, 'change', this.render);
this.render();
},

tagName: 'li',

template: _.template( $('#item-template').html() ),

render: function() {
var temp = this.template({model: this.model.toJSON()});

this.$el.html( temp );
},

events: {
'click': 'toggleActive'
},

toggleActive: function(e) {
this.model.set('isActive');
console.log(this.model.toJSON());
}
});

var theCollection = new TheCollection(data);

var listView = new ListView({collection: theCollection});
listView.render();

模板:

<div class="js-container"></div>

<script type="text/template" id="item-template">
<span <% if (model.isActive === true) { %> class="active" <% } %>>
<%- model.name %>
</span>
</script>

最佳答案

试试这个 http://jsfiddle.net/ManikandanK/c477rone/1/有两件事你需要纠正。

ensureSingleActive: function(current) {
if(current.get('isActive') ) {

var previous= _.find(this.models, function(model) {
return model != current && model.get('isActive')
});

if (previous) {
previous.set('isActive', false);
}
}
}

当您进入此函数时,当前模型值已经设置。所以你不需要再次设置该值。您错过了将值传递给设置函数。

this.model.set('isActive', true);

关于javascript - 随时将 Active 属性仅设置为 Backbone Collection 中的 1 个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28033487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com