在JQM ajax单页导航上修复淘汰多个绑定

时间:2014-03-24 06:26:24

标签: jquery jquery-mobile cordova knockout.js

正在使用Windows 8 phonegap应用程序。我使用的是JQuery,JQuery Mobile,Knockout JS。有点坚持普遍错误

" 您无法多次将绑定应用于同一元素"

谷歌搜索给了我两个解决方案。

1)Ko.cleanNode(不建议)

2)模板化(推荐方法)

我试图采用推荐的模板方法但仍然遇到了同样的错误。

以下是我的javascript逻辑:

//Code for home.js

//My View model
function HomeViewModel() {
    var self = this;
    self.MyDaySchedule = [
        { picture: "../../images/home/MyDaySchedule_video.png" },
        { day: "2", title: "Physical Activity after surgery", text: "you will have tasks each day to help gain strength. Complete self-assessments...", picture: "../../images/home/MyDaySchedule_b1.png" }
    ];
}
//Main Execution
function initialize() {
    console.log("Knockout activated");
    // Activates knockout.js

    ko.applyBindings(new HomeViewModel(), document.getElementById("#homePage"));
}

我将在pageshow事件中调用initialize函数。绑定将正确发生,不会出现任何错误,并且在运行应用程序时将显示所有数据值。

以下是我的html代码,其中包含基于模板的方法:

//home.html
//Binding one
   <div data-bind="template: { name: 'frame1data1-template', data: MyDaySchedule[0] }">  </div>
                            <script type="text/html" id="frame1data1-template">
                                <!-- Displays the "picture" field. -->
                                <img data-bind="attr:{src: picture}"
                                     id="frame1data1_img" draggable="false" />
                            </script>


//Binding two
<div data-bind="template: { name: 'frame1data2-template', data: MyDaySchedule[1] }"></div>
                            <script type="text/html" id="frame1data2-template">
                                <img data-bind="attr:{src: picture}"
                                     src="#" id="frame1data2_img" draggable="false" />
                                <h1 id="frame1data2_daytext" class="disabletextselect">Day</h1>
                                <h1 id="frame1data2_dayvalue" class="disabletextselect" data-bind="text:day"></h1>
                                <h1 id="frame1data2_title" class="disabletextselect" data-bind="text:title"></h1>
                                <h1 id="frame1data2_text" class="disabletextselect" data-bind="text:text"></h1>
                                <input type="button" id="frame1data2_backpicture" data-role="none">
                            </script>

考虑点击上面的任何图片,我使用$ .mobile.navigate(&#34; new.html&#34;)导航到new.html; (这完美无缺)

当我使用window.history.back();从new.html导航回home.html时出现错误。这给我带来了错误&#34; 你不能多次将绑定应用于同一个元素&#34;因为我使用模板方法再次调用ko.applyBindings()。

对于我的示例,此错误是否有积极合适的解决方法?

1 个答案:

答案 0 :(得分:0)

我会将您的个人页面视图模型放在根视图模型中。然后只需使用根视图模型applyBindings,并使用data-bind="with: HomeViewModel()"作为主页模板,对其他页面使用相同的。{/ p>