在一些Knockout例子中,直接在htm中添加scripts写viewmodel,如何能将让ViewModel从htm中剥离出去呢?从knockout官网上找到了解决方法,如下:

1.knockout.htm

<html>
<head>
    <script type="text/javascript" data-main="init.js" src="require.js"></script>
</head>
<body>
    <p>First name:
        <input data-bind="value: firstName" /></p>
    <p>First name capitalized: <strong data-bind="text: firstNameCaps"></strong></p>
</body>
</html>

2.init.js

require(['knockout-2.1.0', 'appViewModel'], function (ko, appViewModel)
{
    ko.applyBindings(new appViewModel());
});

3.appViewModel.js

define(['knockout-2.1.0'], function (ko) {
    return function appViewModel() {
        this.firstName = ko.observable('Bert');
        this.firstNameCaps = ko.computed(function ()
        {
            return this.firstName().toUpperCase();
        }, this);
    };
});

这样就不必在htm中写一大堆js代码了。

 

 

相关文章:

  • 2021-09-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-19
  • 2021-08-10
  • 2022-12-23
  • 2021-04-02
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-20
  • 2021-11-26
  • 2021-09-25
  • 2022-12-23
  • 2022-03-03
相关资源
相似解决方案