2014-11-16 47 views
0

我正在學習Enyo js框架中的事件,並且無法理解爲什麼我得到的錯誤和事件onModelChanged未處理。錯誤消息是 「遺漏的類型錯誤:未定義是不是一個函數」簡單示例中未處理和未定義Enyo自定義事件

代碼:

debugger; 
enyo.kind({ 
    name : "MyModel", 
    kind: "enyo.Model", 
    defaultSource: "mocked", 
    published: { 
     title : "not set", 
     text : "not set",  
    }, 

    events : { 
     onModelChanged : "", 
    }, 

    handlers: { 
     onModelChanged : "modelLoadedHandler" 
    }, 

    modelLoadedHandler : function(inSender, inEvent){ 
     debugger; 
     console.log("handler in model"); 
     console.log(inEvent.textMsg); 
     return true; 
    }, 

    fetch : function(opts){ 
     this.inherited(arguments); 
     debugger; 
     this.doModelChanged({textMsg: "fire event"}); // Uncaught TypeError: undefined is not a function 

    }  

}); 



var model = new MyModel(); 
model.fetch(); 

附:保持此代碼作爲一個答案不通過的jsfiddle

enyo.kind({ 
    name: "MyMockSource", 
    kind: "enyo.Source", 
    fetch: function(model, opts) { 
     if(model instanceof enyo.Model) { 
      opts.success({title: "testing", text: "Some stuff"}); 
     } else { 
      throw new Error("Model mock only"); 
     } 
    } 
}); 

new MyMockSource({name: "mocked"}); 

enyo.kind({ 
    name : "MyModel", 
    kind: "enyo.Model", 
    source: "mocked", 
    attributes: { 
     title : "not set", 
     text : "not set",  
    }, 
    fetched: function(opts){ 
     this.inherited(arguments); 
     enyo.log("fetched"); 
     // Do something here if you need to, otherwise you might want to overload 
     // the parse method and set parse: true to modify the retrieved data 
    }, 
    titleChanged: function(was, is) { 
     enyo.log("Title is now: " + is); 
    } 
}); 

enyo.kind({ 
    name: "MyView", 
    components: [ 
     {kind: "Button", content: "Fetch", ontap: "fetch"}, 
     {name: "title"}, 
     {name: "text"} 
    ], 
    bindings: [ 
     {from: "model.title", to: "$.title.content"}, 
     {from: "model.text", to: "$.text.content"} 
    ], 
    fetch: function() { 
     this.set("model", new MyModel()); // Probably want to create model elsewhere 
     this.model.on("change", enyo.bindSafely(this, "modelChanged")); 
     this.model.fetch(); 
    }, 
    modelChanged: function() { 
     this.log("Something happened to my model!"); 
    } 
}); 

new enyo.Application({ name: "app", view: "MyView" }); 

回答

1

enyo.Model不是enyo.Object(更不用說enyo.Component)。它不支持發佈的屬性或事件。您想要爲模型定義attributes。您仍然可以使用propertyChanged事件或使用observers獲取有關財產更改的通知。

另外,如果您想知道提取已完成,您可能要重載fetchedfetch可能在數據被提取之前返回。

如果您想訂閱來自外部的那麼事件,你可能要綁定到該模型或使用model.on('change')(注意,這是從其他地方使用的events: []系統不同的事件系統changed事件的特定屬性。

更新:這是顯示的各種方法與模型工作,並結合數據

http://jsfiddle.net/RoySutton/5jo0p7ar/

+0

對不起小提琴,我在JS和UI新,並沒有抓到你的意思之外的事件是什麼。但如何解決這個代碼,使我按我期望的方式工作嗎? –

+2

我的意思是說,如果你想從一個不是模型本身的對象中從模型中捕捉事件。增加了工作小提琴。 – Pre101

1

當你以這種方式使用的事件系統中刪除,你通常期望的成分越往上鍊來處理onModelChanged事件,而不是組件定義事件。此外,我相信enyo.Model是一種特殊情況,使用了不同的觀察者機制。這可能是爲什麼你得到「未定義」的函數調用,因爲onModelChanged和doModelChanged方法之間沒有魔術映射。