Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

javascript - Backbone change model of View

I am fairly new to Backbone and have the following question:

I have a collection of models.

I have a collection view displaying tabs (with a view for each model in the collection).

I have a view for a model (for the content).

I have a router with routes.

What I am trying to achieve is a functionality like http://jqueryui.com/demos/tabs/

I click on a tab (model of collection) and then want to pass the model to the content view maybe change it and reflect the changes in the collection.

I came up with four solutions:

In the router:

'switchCommunity': function(id) {
        // (a) set new model attributes
        this.view.community.model.set(communities.get(id));

        // (b) replace model
        this.view.community.model = communities.get(id);

        // (c) a custom function of the view changes its model
        this.view.community.changeModel(communities.get(id));

        // (d) a new view
        this.view.community = new View({
            model: communities.get(id)
        })
}

The problem here is

  • (a) does not reflect changes to the model in the collection

  • (b) does not trigger (change) events, because the bind in the initialize function of the view never triggers, because it is a completly new model

  • (c) seems like a hack to me

  • (d) everytime i click on a tab a new view is created (is this a performance issue?)

What is the best pratice here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One of your solution is close to be okay :D

Here is what you want:

this.view.community.model.set(communities.get(id).toJSON());

And this will trigger model.on("change") as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...