簡體   English   中英

使用Backbone.history時如何處理修改后的模型

[英]How to deal with modified models when using Backbone.history

我下面有這個相當簡單的controller + router作為示例。 我的問題是:如果我修改了某個模型,該如何處理路由器和Backbone.history

假設我啟動了route r和controller 默認路線""將我帶到blue功能,其中我將背景設置為藍色。 我可以單擊將使我進入red功能的按鈕,該按鈕將背景紅色和URL設置為/#red

如果單擊“后退”按鈕,我將返回""網址,但背景將保持紅色。 有沒有一種方法可以獲取以前的狀態,而不僅僅是在處理歷史記錄時更改URL?

我知道在函數blue ,我可以將背景設置為藍色,而不是this.model.get("background) ,但是我想在更復雜的情況下,如何通過以下方式獲取this.model的先前狀態Backbone.history

MyApp.module('Main', function (Main, MyApp, Backbone, Marionette, $, _){

    Main.Router = Marionette.AppRouter.extend({
        appRoutes: {
             "": "blue",
            "red": "red"
        }
    });

    Main.Controller = Marionette.Controller.extend({
        start: function() {
            console.log("MyApp Controller start...");

            this.model = new Backbone.Model({background: "blue"});

            Backbone.history.start()
        },

        blue: function() {
            $("body").css("background-color", this.model.get("background"));            

            $("#button").click(function() {
                //MyApp.router.navigate("red", {trigger: true});
                MyApp.controller.red();
            });
        },

        red: function() {
            this.model.set({background: "red"});
            $("body").css("background-color", this.model.get("background"));
            MyApp.router.navigate("red");
        }
    });
});

MyApp.router.navigate("red"); -這只會更改url,但實際上不會觸發您的控制器方法被觸發。 您可能會想設置{trigger:true}選項,但是要避免這樣做

只需為該路由調用controller方法即可。 我在這里的答案中有一個非常相似的工作示例設置: 如何在Marionette.js中顯示和隱藏區域?

事實是,您的代碼示例中有些事情搞砸了。 就像,您不應該在控制器中設置點擊手柄,這是視圖的工作。 控制器應該只執行最抽象的工作,例如清理和渲染視圖。 實際的用戶交互應在視圖中處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM