如何使用ko属性避免运行代码两次

时间:2013-06-18 20:49:16

标签: javascript knockout.js single-page-application durandal momentjs

我正在创建一个列表页面,其中有两个datepicker和一个表。页面的概念是使用默认参数为日期选择器加载具有一些注册数据的页面,之后用户将能够根据日期选择器过滤器选择他想要查看的内容。为了运行我的应用程序,我创建了两个属性fromDate和toDate,我使用suscribe方法,以便知道日期何时更改,以便在更改日期时,我应该调用我的服务(或一些过滤代码)。我的页面问题是,目前加载我的页面控件默认是从我自己的逻辑中选择的,所以应该调用我的服务的代码被调用两次(一个在loadInitData中,另一个在suscriptions中)

define(["require", "exports", 'services/logger',  '../../services/Assessment/datacontext'], function(require, exports, __logger__, __datacontext__) {
var logger = __logger__;

var datacontext = __datacontext__;    
exports.title = 'AssessmentListing';   
exports.fromDate = ko.observable(new Date('2012/12/12'));
exports.toDate = ko.observable(new Date('2012/12/12'));

function activate() {
   loadInitData();
}

exports.activate = activate;
function loadInitData() { 
   var focusDate = ko.observable(new Date('2013/07/06'));
   exports.fromDate(firstDayOfMonth(focusDate));
   exports.toDate(getLastDayOfMonth(focusDate));
   // calls to services
} 

exports.toDate.subscribe(function (newValue) {
   /*THIS CODE SHOULD BE EXECUTED JUST WHEN THE USER CHANGE THE DATE FROM THE CONTROL*/
   alert("new selection :");
});
exports.fromDate.subscribe(function (newValue) {
   /*THIS CODE SHOULD BE EXECUTED JUST WHEN THE USER CHANGE THE DATE FROM THE CONTROL*/
   alert("new selection");
});

function getLastDayOfMonth(focusDate) {
  var d = new Date(Date.apply(null, focusDate));
  d.setMonth(d.getMonth() + 1);
  d.setDate(0);
  return d;
}

function firstDayOfMonth(focusDate) {
   var d = new Date(Date.apply(null, arguments));
   d.setDate(1);
   return d;
}

function viewAttached() {
}
exports.viewAttached = viewAttached;
})

尝试添加一个新的布尔属性来说明在loadInitData开始时加载(true)和加载(false)以及loadInitData的结尾。这项工作很好。但仍然会多次调用suscription代码。

1 个答案:

答案 0 :(得分:1)

解决此问题的一种简单方法可能是在您的视图模型初始化之前延迟设置订阅:

function activate() {
   loadInitData();

    exports.toDate.subscribe(function (newValue) {
       /*THIS CODE SHOULD BE EXECUTED JUST WHEN THE USER CHANGE THE DATE FROM THE CONTROL*/
       alert("new selection :");
    });
    exports.fromDate.subscribe(function (newValue) {
       /*THIS CODE SHOULD BE EXECUTED JUST WHEN THE USER CHANGE THE DATE FROM THE CONTROL*/
       alert("new selection");
    });
}