当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Count or Select Backbone View Instances

问题描述:

Let's say I'm trying to create a toDo application, where clicking each toDo opens an edit form for each toDoItem. I only want a maximum of one edit form open at any one time, so right now I am doing this in the edit method of the toDoItem view:

edit: function (e) {

e.preventDefault();

if ($('.editForm').length == 0) {

//create form model and view

}

}

That works, but doesn't seem very Backbone-y. Is there are way to select or count all instances of a particular view (in this case, the form-view)?

网友答案:

AFAIK, there are no utilities method in Backbone.View to count instances of a particular Views. Here are some ideas...

  1. Maybe each of your TODO form is tied to a Model? In that case, you can have a model.set/get 'editing' and a collection.isAlreadyEditing() which would filter the models on this field:

    (collection.filter(function(model){ return model.get("editing") }).length > 0

    That would allow you to use on change:editing events throughout your views to control the logic and have convenient helpers functions in the collection to define some behavior of all those TODO as a whole. This would be one way to implement something closer to a Controller pattern in Backbone.

  2. Another common thing in backbone is to keep an array of all the subviews when you instanciate them, so you could just do a:

    _.any(subViews, function(view){return view.editing; })

    Assuming that you keep a editing flag in your subviews when it gets toggled.

  3. You can have your views listen to a toggleEdit event with the id or the model or something identifying what is being edited, sometimes the event handler can be as simple as a toggleClass("open", model==this.model)...

I am sure there are millions of other ideas. But counting jQuery selected elements is probably not very high on the list!

分享给朋友:
您可能感兴趣的文章:
随机阅读: