Skip to content

Commit

Permalink
Merge pull request knockout#972 from knockout/972-style-value-zero
Browse files Browse the repository at this point in the history
bug in 'style'-binding
  • Loading branch information
rniemeyer committed Jun 11, 2014
2 parents e2db8d8 + af42454 commit d12f329
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
14 changes: 14 additions & 0 deletions spec/defaultBindings/styleBehaviors.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,18 @@ describe('Binding: CSS style', function() {
myObservable(undefined);
expect(testNode.childNodes[0].style.backgroundColor).toEqual("");
});

it('Should be able to apply the numeric value zero to a style', function() {
// Represents https://github.com/knockout/knockout/issues/972
testNode.innerHTML = "<div data-bind='style: { width: 0 }'></div>";
ko.applyBindings(null, testNode);
expect(testNode.childNodes[0].style.width).toBe("0px");
});

it('Should be able to use "false" to remove a style', function() {
// Verifying that the fix for 972 doesn't break this existing behaviour
testNode.innerHTML = "<div style='width: 100px' data-bind='style: { width: false }'></div>";
ko.applyBindings(null, testNode);
expect(testNode.childNodes[0].style.width).toBe("");
});
});
8 changes: 7 additions & 1 deletion src/binding/defaultBindings/style.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ ko.bindingHandlers['style'] = {
var value = ko.utils.unwrapObservable(valueAccessor() || {});
ko.utils.objectForEach(value, function(styleName, styleValue) {
styleValue = ko.utils.unwrapObservable(styleValue);
element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect

if (styleValue === null || styleValue === undefined || styleValue === false) {
// Empty string removes the value, whereas null/undefined have no effect
styleValue = "";
}

element.style[styleName] = styleValue;
});
}
};

0 comments on commit d12f329

Please sign in to comment.