Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ajax加载的模板_Ajax_Knockout.js_Sammy.js - Fatal编程技术网

Ajax加载的模板

Ajax加载的模板,ajax,knockout.js,sammy.js,Ajax,Knockout.js,Sammy.js,我在处理这个案件的各种可能性之间迷失了方向:假设我们有以下限制: 击倒 带有Sammy.js的SPA-通过Ajax加载Html 我的页面: +-------------------------------+ | #navigation | +---------+---------------------+ | #sidebar| #content | | | | |

我在处理这个案件的各种可能性之间迷失了方向:假设我们有以下限制:

  • 击倒
  • 带有Sammy.js的SPA-通过Ajax加载Html
我的页面:

+-------------------------------+
| #navigation                   |
+---------+---------------------+
| #sidebar|    #content         |
|         |                     |
|         |                     |
|         |                     |
+---------+---------------------+
目前,我有一个appViewModel,它处理我网站中所有共享元素的数据绑定:#导航和#侧边栏。这个appViewModel已经在我的网站的每个页面上使用

appViewModel = function () {
    var self = this;
    self.sidebarItemArray = ko.observableArray([x, y, z]);
    self.currentRoute = ko.observable();

    ...

    self.updateView = function(path, currentRoute) {
        return $.get(path, function( data ) {
            var $data = $(data);
            // Updates #content, TITLE and update the currentRoute observable.
            $( '#content' ).replaceWith($data.find('#content'));
            document.title = $data.filter('title').text();
            self.currentRoute(currentRoute);
            }, 'html');
    }

    Sammy(function() {
        this.get(':link'', function() {
            self.updateView(this.path, this.params.link);
        });
    }).run();
}
ko.applyBindings(new appViewModel());
现在,假设内容是通过Ajax调用加载的DOM。每次用户单击#导航或#侧边栏中的链接时,Sammy.js都会截取它,然后更新内容。问题在于,内容中的新DOM本身具有数据绑定

1) 首先,我应该使用#content上的html数据绑定、replacetwith(如上所述)还是使用带有自定义函数的模板绑定来获取模板? ()? 这里的最佳做法是什么

2) Sammy在appViewModel中的必要生命(如文档中或其他地方)是否可以

3) 一旦updateView方法完成,您将如何绑定新的DOM?像下面这样?因为已经在没有第二个参数的情况下调用了ko.applyBindings,是否存在重新绑定某些DOM的风险

ko.applyBindings(new routeSpecificViewModel() , document.getElementById("content")); 

感谢您的帮助。

一个简单的解决方案是将页面的viewmodel设置为可观察的,并按需加载。使用变量记录是否调用了ko.applyBindings。来自淘汰spa框架的示例:

/*! knockout-spa (https://github.com/onlyurei/knockout-spa) * Copyright 2015-2016 Cheng Fan * MIT Licensed (https://raw.githubusercontent.com/onlyurei/knockout-spa/master/LICENSE) */

define(['app/shared/root-bindings', 'framework/page-disposer', 'ko', 'sugar'], function (
  RootBindings, PageDisposer, ko) {

  var initialRun = true;

  var Page = {
    init: function (name, data, controller, path) {
      Page.loading(false);

      name = name.toLowerCase();

      if ((Page.page().name == name) && (Page.page().data == data)) { // if the requested page is the same page, immediately call controller without going further
        if (controller) {
          controller(data);
        }

        document.title = Page.title();

        if (Page.initExtra) {
          Page.initExtra(name, data, controller);
        }

        return data;
      }

      var autoDispose = (Page.page().data.dispose && Page.page().data.dispose(Page)) || true; // if the requested page is not the same page, dispose current page first before swap to the new page
      if (autoDispose !== false) {
        // auto-dispose page's exposed observables and primitive properties to initial values. if not desired, return
        // false in dispose function to suppress auto-disposal for all public properties of the page, or make the
        // particular properties private
        PageDisposer.dispose(Page.page().data);
      }

      PageDisposer.init(data); //store initial observable and primitive properties values of the page
      var initialized = (data.init && data.init(Page)) || true; // init view model and call controller (optional) before template is swapped-in
      if (initialized === false) {
        return false; // stop initialization if page's init function return false (access control, etc.)
      }
      if (controller) {
        controller(data);
      }

      Page.pageClass([name, ('ontouchstart' in document.documentElement) ? 'touch' : 'no-touch'].join(' '));
      Page.page({
        name: name,
        data: data,
        path: path
      }); // to test if template finished rendering, use afterRender binding in the template binding

      document.title = Page.title();

      if (Page.initExtra) {
        Page.initExtra(name, data, controller); // useful for common init tasks for all pages such as anaylitics page view tracking, can be set in RootBindings
      }

      if (initialRun) {
        ko.applyBindings(Page, document.getElementsByTagName('html')[0]); // apply binding at root node to be able to bind to anywhere
        initialRun = false;
      }

      return data;
    },
    page: ko.observable({
      name: '', // name of the page - auto-set by the framework, no need to worry
      data: {
        init: function () {}, // preparation before the page's template is rendered, such as checking access control, init/instantiate modules used by the page, etc.
        dispose: function () {} // properly dispose the page to prevent memory leaks and UI leftovers (important for SPA since page doesn't refresh between page views) - remove DOM element event listeners, dispose knockout manual subscriptions, etc.
      }
    }),
    pageClass: ko.observable(''),
    loading: ko.observable(false),
    title: function () {
      return Page.page().name.titleize(); // override in RootBindings as needed
    }
  };

  Object.merge(Page, RootBindings); // additional root bindings as needed by the app

  return Page;

});
在Knockout、Require、Director、jQuery和Sugar之上构建的一个小型但成熟的SPA框架。


现场演示:

因为这已经有一年多的历史了,我想问一下您是否有过解决方案?我面临着同样的困境。老问题:-)我最终使用了淘汰型AMD和requireJs以及flatiron/director作为路由器。这很有魅力。使用此堆栈将创建避免这些问题的约束。