Polymer two way binding - data-binding

Banging my head on how to use polymer two way binding.
I have a home made Polymer element that defines a boolean property through
Polymer({
is: "test-element",
ready: function() {},
properties: {
propEnabled: {
type: Boolean,
notify: true,
value: false,
observer: "propEnabledChanged"
}
},
// Called when aoEnabled is changed
propEnabledChanged: function() { console.log("propEnabled value switched to " + this.propEnabled); },
});
Now I'm using this in an HTML page
<body>
<template id="t" is="dom-bind">
<test-element id="testElement"></test-element>
<paper-toggle-button checked="{{Model.propEnabled}}">prop. enabled</paper-toggle-button>
<button id="switchInternalState">switch state</button>
</template>
</body>
<script>
var t = document.querySelector('#t');
document.addEventListener('WebComponentsReady', function() {
console.log('WebComponentsReady');
// We have to bind the template with the model
var t = document.querySelector('#t');
t.Model = document.getElementById("testElement");
// chaging the property directly does not reflect in the GUI... :-(
var button = document.getElementById("switchInternalState");
button.addEventListener("click", function() {
t.Model.set("propEnabled", !t.Model.propEnabled);
});
});
</script>
But when clicking on the switch state button...
I get the log propEnabled value switched to true
But the toogle button on the page does not change...
If I add a simple
<label>{{Model.propEnabled}}</label>
The label does not change either...
To me it looks a bit like one way binding where it should be 2 way as
toggling the button fire the log and properly change the component propEnabled value. So it really looks like one way binding to me.
So... How can we actually benefit from two way binding with Polymer templates ????

You need to assign the propEnabled property from dom-bind to the test-element through html.
<test-element id="testElement" prop-enabled={{propEnabled}}></test-element>
<paper-toggle-button checked="{{propEnabled}}">prop. enabled</paper-toggle-button>
Also you don't need the variable t.Model in your script. You can remove it. The event listener should be like below
button.addEventListener("click", function() {
t.propEnabled = !t.propEnabled;
});
The following plunker has the working code: http://embed.plnkr.co/13QJ7QFETIBg4bEiCMS7/preview

Related

Can Ractive events work in markup rendered with the triple-stash syntax?

If I have the following in my Ractive template:
<span on-click='handleClick'>click me</span>
Then I can listen for the click with this:
app.on({
handleClick:function() {
alert("clicked!") ;
}
})
But lets say I have that same markup stored in a string variable called clicklyspan:
app.set("clicklyspan", "<span on-click='handleClick'>click me</span>")
and I render it in the template using the triple-stash syntax:
{{{clicklyspan}}}
The handleClick listener no longer gets fired. Is there anything I can do to force some kind of update to the rendered template so that the listener works? Say, after I do that app.set() call?
Here's a fiddle demonstrating the problem.
Thanks,
Dave
I have never used Ractive, but I did some research and it seems you have to use partials, like this:
var app = new Ractive({
el: 'container',
template: '#template',
data: {
myFunction: function() {
var template = '<a on-click="handleClick">I can now be clicked as well!</a>';
if (!this.partials.myFunction) {
this.partials.myFunction = template;
}
else {
this.resetPartial('myFunction', template);
}
return 'myFunction';
}
}
});
You will also need to use this instead of the triple mustache:
{{> myFunction() }}
Here's the corresponding jsfiddle.
Of course, replace myFunction with whatever name you like.
Related question I found useful:
RactiveJS events on tripple mustache

How to pass functions to capture events in custom component in Meteor with Blaze

I want to know how to bind/set template-passed-parameter-value to click event of an item in the template in Meteor.
I'm using Meteor 0.7.0.1 with Blaze UI package. My main idea is to build a re-usable custom components in Meteor with Blaze template engine.
I have the following component which is working fine at the moment but I want this to be more customizable and remove some dependencies.
This is my component template named postLinks
<template name="postLinks">
<div id="link-popover-wrapper" >
<ul class="link-popover">
{{#each linkOptions}}
<li><a tabindex="-1" class="link-action" id="link-{{value}}" href="#">{{label}}</a>
</li>
{{/each}}
</ul>
</div>
</template>
This postLinks component is used in the myPostItem helper.
Template.myPostItem.events({
'click .post-item-link-picker': function (evt, tmpl) {
var tmpPostId = this._id;
var tempData = {linkOptions:[{label:'Favorite', value : 'favorite'},{label:'Wish list', value : 'wishlist'},{label:'Later', value : 'later'}, {label:"Read", value:"read"}]};
var linkContent = Template.postLinks(tempData);
$(".item-link-picker").popover({
content: linkContent, html: true, placement: 'bottom', trigger: "manual",
template: "UI_POPOVER_TEMPLATE"});
$("#item-link-picker-"+tmpPostId).popover('show');
},
'click .link-action': function (evt, tmpl) {
//.... some code here to update link selection in db
}
});
Above code is working fine and I want to improve it to have following
Pass item click event externally to be bind to link-action like
After above two changes it will look like :
Template.myPostItem.events({
'click .post-item-link-picker': function (evt, tmpl) {
var tmpPostId = this._id;
var tempData = { itemClick:function(){}, linkOptions:[{label:'Favorite', value : 'favorite'},...]};
var linkContent = Template.postLinks(tempData);
$(".item-link-picker").popover({
content: linkContent, html: true, placement: 'bottom', trigger: "manual",
template: "UI_POPOVER_TEMPLATE"});
$("#item-link-picker-"+tmpPostId).popover('show');
}
});
I lack knowledge how/where to bind that passed event handling function to link-action elements in template or helper. I really appreciate if anybody could help to find a way to do that.
You go the other way around and use jQuery event triggering system, so
Template.myPostItem.events({
'click .link-action': function (evt, tmpl) {
$(evn.target).trigger('post-link-action', this /* extra data */);
},
});
This event can be easily catched in any parent template:
<template name="someOtherTamplate">
{{> myPostItem}}
</template>
Template.someOtherTemplate.events({
'post-link-action': function (evt, tmpl, extra) {
// the user of your component can define their custom behavior here
},
});
Please note that the event extra parameter will only be supported in the next Meteor release. Currently (0.8.0) it is included in the devel branch.

Bootboxjs: how to render a Meteor template as dialog body

I have the following template:
<template name="modalTest">
{{session "modalTestNumber"}} <button id="modalTestIncrement">Increment</button>
</template>
That session helper simply is a go-between with the Session object. I have that modalTestNumber initialized to 0.
I want this template to be rendered, with all of it's reactivity, into a bootbox modal dialog. I have the following event handler declared for this template:
Template.modalTest.events({
'click #modalTestIncrement': function(e, t) {
console.log('click');
Session.set('modalTestNumber', Session.get('modalTestNumber') + 1);
}
});
Here are all of the things I have tried, and what they result in:
bootbox.dialog({
message: Template.modalTest()
});
This renders the template, which appears more or less like 0 Increment (in a button). However, when I change the Session variable from the console, it doesn't change, and the event handler isn't called when I click the button (the console.log doesn't even happen).
message: Meteor.render(Template.modalTest())
message: Meteor.render(function() { return Template.modalTest(); })
These both do exactly the same thing as the Template call by itself.
message: new Handlebars.SafeString(Template.modalTest())
This just renders the modal body as empty. The modal still pops up though.
message: Meteor.render(new Handlebars.SafeString(Template.modalTest()))
Exactly the same as the Template and pure Meteor.render calls; the template is there, but it has no reactivity or event response.
Is it maybe that I'm using this less packaging of bootstrap rather than a standard package?
How can I get this to render in appropriately reactive Meteor style?
Hacking into Bootbox?
I just tried hacked into the bootbox.js file itself to see if I could take over. I changed things so that at the bootbox.dialog({}) layer I would simply pass the name of the Template I wanted rendered:
// in bootbox.js::exports.dialog
console.log(options.message); // I'm passing the template name now, so this yields 'modalTest'
body.find(".bootbox-body").html(Meteor.render(Template[options.message]));
body.find(".bootbox-body").html(Meteor.render(function() { return Template[options.message](); }));
These two different versions (don't worry they're two different attempts, not at the same time) these both render the template non-reactively, just like they did before.
Will hacking into bootbox make any difference?
Thanks in advance!
I am giving an answer working with the current 0.9.3.1 version of Meteor.
If you want to render a template and keep reactivity, you have to :
Render template in a parent node
Have the parent already in the DOM
So this very short function is the answer to do that :
renderTmp = function (template, data) {
var node = document.createElement("div");
document.body.appendChild(node);
UI.renderWithData(template, data, node);
return node;
};
In your case, you would do :
bootbox.dialog({
message: renderTmp(Template.modalTest)
});
Answer for Meteor 1.0+:
Use Blaze.render or Blaze.renderWithData to render the template into the bootbox dialog after the bootbox dialog has been created.
function openMyDialog(fs){ // this can be tied to an event handler in another template
<! do some stuff here, like setting the data context !>
bootbox.dialog({
title: 'This will populate with content from the "myDialog" template',
message: "<div id='dialogNode'></div>",
buttons: {
do: {
label: "ok",
className: "btn btn-primary",
callback: function() {
<! take some actions !>
}
}
}
});
Blaze.render(Template.myDialog,$("#dialogNode")[0]);
};
This assumes you have a template defined:
<template name="myDialog">
Content for my dialog box
</template>
Template.myDialog is created for every template you're using.
$("#dialogNode")[0] selects the DOM node you setup in
message: "<div id='dialogNode'></div>"
Alternatively you can leave message blank and use $(".bootbox-body") to select the parent node.
As you can imagine, this also allows you to change the message section of a bootbox dialog dynamically.
Using the latest version of Meteor, here is a simple way to render a doc into a bootbox
let box = bootbox.dialog({title:'',message:''});
box.find('.bootbox-body').remove();
Blaze.renderWithData(template,MyCollection.findOne({_id}),box.find(".modal-body")[0]);
If you want the dialog to be reactive use
let box = bootbox.dialog({title:'',message:''});
box.find('.bootbox-body').remove();
Blaze.renderWithData(template,function() {return MyCollection.findOne({_id})},box.find(".modal-body")[0]);
In order to render Meteor templates programmatically while retaining their reactivity you'll want to use Meteor.render(). They address this issue in their docs under templates.
So for your handlers, etc. to work you'd use:
bootbox.dialog({
message: Meteor.render(function() { return Template.modalTest(); })
});
This was a major gotcha for me too!
I see that you were really close with the Meteor.render()'s. Let me know if it still doesn't work.
This works for Meteor 1.1.0.2
Assuming we have a template called changePassword that has two fields named oldPassword and newPassword, here's some code to pop up a dialog box using the template and then get the results.
bootbox.dialog({
title: 'Change Password',
message: '<span/>', // Message can't be empty, but we're going to replace the contents
buttons: {
success: {
label: 'Change',
className: 'btn-primary',
callback: function(event) {
var oldPassword = this.find('input[name=oldPassword]').val();
var newPassword = this.find('input[name=newPassword]').val();
console.log("Change password from " + oldPassword + " to " + newPassword);
return false; // Close the dialog
}
},
'Cancel': {
className: 'btn-default'
}
}
});
// .bootbox-body is the parent of the span, so we can replace the contents
// with our template
// Using UI.renderWithData means we can pass data in to the template too.
UI.insert(UI.renderWithData(Template.changePassword, {
name: "Harry"
}), $('.bootbox-body')[0]);

jquery accordion effect doesnt work when I use ajax

When I use ajax, I noticed that Jquery effects don't work. The reason is "The new HTML you're adding to the DOM (page) didn't exist when your jquery ran the first time "
another similar question
Therefore, I changed my code to following but still I don't get the jquery effects.
Where I have done the mistake?
Previous code
$("#sendemp").click(function(e) {
e.preventDefault();
var submit_val = $("#searchbox").val();
//alert('submitval is ' + submit_val);
$.ajax( {
type : "POST",
//dataType :"jason",
url : "./wp-admin/admin-ajax.php",
data : {
action : 'employee_pimary_details',
user_name : submit_val
},
success : function(data) {
// alert('hhh');
$('#accordion21').html(data);
// $( "#searchbox" ).autocomplete({
// source: data
// });
}
});
});
New code
$("button").on( "click", "#accordion3",function(){
$.ajax( {
type : "POST",
dataType : "json",
url : "./wp-admin/admin-ajax.php",
data : {
action : 'employee_deatils_search',
user_name : submit_val
},
success : function(data) {
// alert('hhh');
$('#accordion3').html(data);
$("tr:odd").css("background-color", "#F8F8F8");
$("#accordion3").accordion({ heightStyle: "fill", active: 0 });
// $( "#searchbox" ).autocomplete({
// source: data
// });
}
});
} );
I have following submit button
<input type="submit" id="sendemp" value="Search" />
I don't think your click binding is correct, if you want to handle clicks on button inside #accordion3 change it to:
$("#accordion3").on( "click", "button",function(){...});
It is hard to tell without your html, but it looks like in your old code you are replacing the sendemp button. In your new code your event delegation is incorrectly specified. You are applying delegation to a button element (which doens't exist since your sendemp button is an input element).
Apply delegate to something that is the parent of #sendemp like so:
$('body').on('click', '#sendemp', function() {
// your ajax call
});
I could fix the issue, I tried the above solution that is using on method. However, it doesn't make sense to my problem.
As following artical explain I think, Accordion is already instantiated and effects are persistance. When it is called second time, it won't create again since there is already the effects.
Therefore, I needed to destroy it and recreate accordion.
support link
I changed the code on success as follows
success : function(data) {
// alert('hhh');
$('#accordion3').accordion('destroy');
$('#accordion3').html(data);
$("tr:odd").css("background-color", "#F8F8F8");
//$("#accordion3").accordion( "disable" );
$("#accordion3").accordion({ active: 0 });
}
And out of $(document).ready(function() {
I added
$(function() {
$("#accordion3").accordion({
// heightStyle: "fill",
active: 0 });
});

knockout css dynamic binding

I am working on a little project with knockout where i have to simulate the answer to asome questions.
I dynamically build 3 buttons and when i click one i compare the text on it with the correct answer and if it's correct it should become green.., if it's not correct it should become red and the right one should become green..
I was trying to use the binding to css property of knockout, but it seems that the property is not correctly refreshed, even if the computed associated with the css changes
The html:
<ul data-bind="foreach: chosenQuestionAnswers">
<li>
<button data-bind="text: answerText, css: $root.answerStatus(), click: $root.selectButton"></button>
</li>
</ul>
The ko part:
selectedAnswer: ko.observable(),
isAnswerCorrect: ko.observable(),
selectButton: function (value) { my.AppViewModel.isAnswerCorrect(my.AppViewModel.checkIfCorrectAnswer(value.answerText));
},
checkIfCorrectAnswer: function (value) {
return (value == my.AppViewModel.chosenQuestionCorrectAnswer());
},
my.AppViewModel.answerStatus = ko.computed(function () {
var exit = this.isAnswerCorrect() == true ? "highlightRight" : "highlightWrong";
console.log(this.isAnswerCorrect());
console.log(exit);
return exit;
}, my.AppViewModel);
The console.log shows the correct value of the var exit... but the css of the button does not change...
Any idea why?..
Thanks.... I.
you're referencing an old version of KO (2.1), the latest as of today is version is 2.2.1. Your fiddle works when referencing the new version # http://knockoutjs.com/downloads/knockout-2.2.1.js. Here's a fork: http://jsfiddle.net/drdamour/xe2M5/
The dynamic css binding (how you're using it) was only added in 2.2 see http://blog.stevensanderson.com/2012/10/29/knockout-2-2-0-released/
stack won't let me submit without some code so...here some worthless code:
var x = {a:1}
css classes are part of the view, try to keep them out of the ViewModel, it should focus on business logic.
I would do something like
http://jsfiddle.net/hLXbq/
HTML
<button data-bind="css: { valid: valid, invalid: invalid }, click: toggle">Toggle</button>
JS
ViewModel = function () {
this.valid = ko.observable(false);
this.invalid = ko.computed(function () {
return !this.valid();
}, this);
};

Resources