2016-08-22 41 views
0

我試圖使用需要js的Knockout,但我無法綁定來自viewmodel的數據。RequireJs with Knockout

HTML

<!doctype html> 
<html lang="en"> 
<head> 
    <title>SPA</title> 
    <!-- Load the script "js/main.js" as our entry point --> 
    <script data-main="js/app" src="js/lib/require.js"></script> 
</head> 
<body> 

Today's message is: <span data-bind="text: myMessage"></span> 

</body> 
</html> 

app.js

requirejs.config({ 
    "baseUrl": "js/lib", 
    "paths": { 
     "app": "../app", 
     "jquery": "jquery", 
     "knockout-3.4.0":"knockout-3.4.0", 
     "custom":"../custom/custom-script", 
     "customKO":"../custom/custom-knockout" 

    } 
}); 
require(['knockout-3.4.0', 'customKO'], function(ko, appViewModel) { 
    ko.applyBindings(new appViewModel()); 
}); 
// Load the main app module to start the app 
requirejs(["app/main"]); 

main.js

define(["jquery", "knockout-3.4.0", "jquery.alpha", "jquery.beta" , "custom" , "customKO"], function($ , ko) { 
    //the jquery.alpha.js and jquery.beta.js plugins have been loaded. 
    $(function() { 
     $('body').alpha().beta(); 

    }); 

}); 

custon-knockout.js

//Main viewmodel class 
define(['knockout-3.4.0'], function(ko) { 
    return function appViewModel() { 
     var viewModel = { 
     myMessage: ko.observable() // Initially blank 
    }; 
    viewModel.myMessage("Hello, world!"); // Text appears 
    }; 
}); 

但我得到下面的錯誤

未捕獲的ReferenceError:無法處理的綁定 「文本:函數(){返回} myMessage」 消息:myMessage沒有定義

回答

2

你(使用new)調用appViewModel作爲構造,但創造它裏面的局部變量viewModel ,而不是將成員添加到this,如this.myMessage = ko.observable();

0

你的arent生產,可以構建一個類,並返回性能

define(['knockout-3.4.0'], function(ko) { 
    return function appViewModel() { 
     var self = this; 
     self.myMessage: ko.observable() // Initially blank 
     self.myMessage("Hello, world!"); // Text appears 
     }; 
    }; 
}); 
相關問題