2013-03-07 94 views
0

我在我的应用程序中有以下javascript定义的页面,我试图在其中使用knockout。Knockout js动态绑定

var dashboard = new DashboardPage(); 

function DashboardPage() { 
    var page = this; 

    page.open = function() { 
     var bindingString = '{ name: "dashboard-template" }'; 
     $('#main div').html("").attr("data-bind", bindingString); 
     ko.applyBindings(new page.ViewModel(), $("#main")[0]); 
    }; 

    page.ViewModel = function() { 
     var self = this; 
     self.content = ko.observable("SOME WORDS"); 
    }; 
    //Other code removed. 

这是模板:

<script type="text/html" id="dashboard-template"> 
    <div id="wrapper-block2" class="wrapper-block"> 
     <div id="content-block2" class="content-block"> 
      Hello 
     </div> 
    </div> 
    <div id="wrapper-block3" class="wrapper-block"> 
     <div id="content-block3" class="content-block"> 
      World 
     </div> 
    </div> 
</script> 

dashboard.open()肯定是被调用,但没有被填充我的#main股利和没有错误。

有人能指出我做错了什么吗?我认为,没有任何错误,ko甚至没有试图绑定任何东西。

回答

1

当你是binding a template时,你不应该使用单词模板吗?

var bindingString = 'template: { name: "dashboard-template" }'; 
+0

是。对,我是。非常感谢@ paul-manzotti – 2013-03-07 16:09:49

0

你需要在data-bind中指定“template”参数,我也认为你的函数的排序可能有点棘手。我认为这是你在找什么:

HTML:

<div id="main" data-bind="template: { name: 'dashboard-template' }"></div> 

<script type="text/html" id="dashboard-template"> 
    <div id="wrapper-block2" class="wrapper-block"> 
     <div id="content-block2" class="content-block" data-bind="text: content"> 
     </div> 
    </div> 
</script> 

JS:

function DashboardViewModel() { 
    var self = this; 

    self.content = ko.observable("SOME WORDS"); 
}; 


$(document).ready(function() { 
    ko.applyBindings(new DashboardViewModel(), $("#main")[0]); 
}); 
+0

感谢@chrisjsherm的回答。 你对模板参数绝对正确。通常会使用$(document).ready,但在这种情况下,我不希望淘汰赛控制页面加载,因为仪表板是以相同方式加载的许多页面之一。 – 2013-03-07 17:04:02