Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...