Skip to content

Commit

Permalink
Merge pull request #27 from derbyjs/custom-condition-equality
Browse files Browse the repository at this point in the history
implement support for custom equality function on condition objects
  • Loading branch information
nateps authored Aug 8, 2018
2 parents 4a8b7d8 + dc7054b commit 8f66978
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,9 @@ Template.prototype.update = function() {};
Template.prototype.stringify = function(value) {
return (value == null) ? '' : value + '';
};
Template.prototype.equals = function(other) {
return this === other;
};
Template.prototype.module = 'templates';
Template.prototype.type = 'Template';
Template.prototype.serialize = function() {
Expand Down Expand Up @@ -752,7 +755,8 @@ Block.prototype.serialize = function() {
Block.prototype.update = function(context, binding) {
if (!binding.start.parentNode) return;
var condition = this.getCondition(context);
if (condition === binding.condition) return;
// Cancel update if prior condition is equivalent to current value
if (equalConditions(condition, binding.condition)) return;
binding.condition = condition;
// Get start and end in advance, since binding is mutated in getFragment
var start = binding.start;
Expand Down Expand Up @@ -824,7 +828,8 @@ ConditionalBlock.prototype.serialize = function() {
ConditionalBlock.prototype.update = function(context, binding) {
if (!binding.start.parentNode) return;
var condition = this.getCondition(context);
if (condition === binding.condition) return;
// Cancel update if prior condition is equivalent to current value
if (equalConditions(condition, binding.condition)) return;
binding.condition = condition;
// Get start and end in advance, since binding is mutated in getFragment
var start = binding.start;
Expand Down Expand Up @@ -1217,6 +1222,14 @@ function escapeAttribute(string) {
});
}

function equalConditions(a, b) {
// First, test for strict equality
if (a === b) return true;
// Failing that, allow for template objects used as a condition to define a
// custom `equals()` method to indicate equivalence
return (a instanceof Template) && a.equals(b);
}


//// Shims & workarounds ////

Expand Down

0 comments on commit 8f66978

Please sign in to comment.