rniemeyer / knockout-postbox

A small library that uses Knockout's native pub/sub capabilities to facilitate decoupled communication between separate view models or components.
MIT License
348 stars 55 forks source link

Unable to use the pub/sub with iframes #11

Closed ishaan-puniani closed 10 years ago

ishaan-puniani commented 11 years ago

hi i am unable to subscribe view model in the iframe with the publisher view model in the container page. Is there any way to do the same, or is there any way to pass a view model from one page to iframe in same domain.?

rniemeyer commented 11 years ago

Yes, there is a way to make something like this work. One technique is to add a function to the window object of the child frame that accepts ko and a view model (if you want to bind the same view model, not necessary if you are using postbox to communicate).

On the child page, you would have a function like:

window.bindMe = function(ko, viewModel) {
     ko.applyBindings(viewModel, document,body);
};

On the parent, you would do something like:

var viewModel = new ViewModel();
ko.applyBindings(viewModel); //on this page
document.getElementById("myChildFrameId").contentWindow.bindMe(ko, viewModel); //on child

Now both pages are dealing with the same instance of Knockout. Let me know if you have problems making this work.

ishaan-puniani commented 11 years ago

hi, i have worked out with this solution but still facing some issues. please see the same below http://jsfiddle.net/Ishaan2990/FuLk4/5/

Thanks for you time.

rniemeyer commented 11 years ago

The iframe doesn't load properly inline. You would need to make sure that your bindMe function is created inside the iframe on its window. Otherwise, you can flip it around and add something like a bindChild function on the parent and call it from the child using window.parent.

Here is a sample: http://jsfiddle.net/rniemeyer/WVJRx/show

You can see the code here: http://jsfiddle.net/rniemeyer/WVJRx/ and for the child here: http://jsfiddle.net/rniemeyer/WVJRx/

The preview in jsFiddle runs under a different sub-domain, which is why the first link shows it working.