Added support for "getInitialProps"

This commit is contained in:
Patrick Steele-Idem 2015-04-02 16:31:12 -06:00
parent 1f620de799
commit fd96c2db8d
4 changed files with 39 additions and 5 deletions

View File

@ -43,6 +43,7 @@ function mergeExtendState(widgetState, widgetArgs) {
module.exports = function defineRenderer(def) {
var template = def.template;
var getInitialProps = def.getInitialProps;
var getTemplateData = def.getTemplateData;
var getInitialState = def.getInitialState;
var getWidgetConfig = def.getWidgetConfig;
@ -60,6 +61,8 @@ module.exports = function defineRenderer(def) {
input = {};
}
if (!loadedTemplate) {
loadedTemplate = template.render ? template : marko.load(template);
}
@ -86,15 +89,21 @@ module.exports = function defineRenderer(def) {
input[k] = global.__rerenderState[k];
}
}
widgetState = getInitialState(input);
} else {
// We are the first widget and we are not being extended
// and we are not extending so use the input as the state
widgetState = input;
input = null;
}
} else {
// We are not the top-level widget so we need to rebuild the state
// from the provided input properties
}
}
if (!widgetState) {
if (getInitialProps) {
input = getInitialProps(input, out) || {};
}
if (getInitialState) {
widgetState = getInitialState(input);
}
}
@ -115,7 +124,7 @@ module.exports = function defineRenderer(def) {
}
var existingWidget = getExistingWidget(out, widgetArgs);
if (existingWidget && (existingWidget.constructor === def.constructor) && shouldReuseWidget(existingWidget, widgetState, input)) {
// console.log(module.id, 'Reusing existing widget ', existingWidget.id, 'New state: ', widgetState);
// Render a placeholder element as a marker that we can use to splice back in the existing

View File

@ -0,0 +1,9 @@
module.exports = require('marko-widgets').defineWidget({
template: require.resolve('./template.marko'),
getInitialProps: function(input, out) {
var name = input.name;
return {
name: name.toUpperCase()
};
}
});

View File

@ -0,0 +1,3 @@
<div w-bind>
Hello ${data.name}!
</div>

View File

@ -200,6 +200,19 @@ describe('widget' , function() {
expect(widget.lifecycleEvents).to.deep.equal(['onBeforeUpdate', 'onAfterUpdate', 'onBeforeDestroy', 'onDestroy']);
});
it('should support getInitialProps', function() {
var targetEl = document.getElementById('target');
require('./fixtures/components/app-getInitialProps')
.render({
name: 'Frank'
})
.appendTo(targetEl)
.getWidget();
expect(targetEl.innerHTML).to.contain('Hello FRANK!');
});
});