As i follow some tuts for angular and ember.js I came across the term Two way data binding. Where data displayed on UI are bind with database and any changes to one is quickly propagated to the other. When I started learning meteor.js i came across term "Reactivity" which for me makes same sense as two way data binding. Can you please tell me fundamental difference between these two terms?
Reactivity is in fact more general than data binding. With reactivity you can implement data binding, in a really simple way, e.g.
var myAwesomeData = "some data";
var myAwseomeDependency = new Tracker.Dependency();
var getData = function () {
myAwesomeDependency.depend();
return myAwesomeData;
};
var setData = function(value) {
if (value !== myAwesomeData) {
myAwesomeData = value;
myAwesomeDependency.changed();
}
}
Now, every time the getData routine is called within a computation, so basically within Tracker.autorun environment, it gets recomputed. By default the meteor's collection API is implemented to be reactive, so every time fetch some data from you'r database you can be sure that it gets updated as soon as the data changes.
Also note, that you can use the above reactivity pattern without any database or values, so for example you can trigger and monitor events, states and so on.
This Wikipedia Article will help you:
http://en.wikipedia.org/wiki/Reactive_programming
It basically says, that changes of data in specific dataLayers are automatically propagated. This paradigm seems to be the generic term and each framework with databinding / two way databinding is building on it and gives their technique a different name.
My understanding is that two-way data binding is a form of reactive programming. Reactive simply means that a flow of changes in your data drives action. Whether the change comes from both the DOM and the data in your application or just one of those, does not really matter.
Related
A first idea would be cookies, yet you can run out of space really fast.
There are several ways to get communication in microfrontends.
As already noted the different microfrontends should be loosely coupled, so you'd never directly talk from one to another.
The key question is: Is your microfrontend solution composed on the server-side or client-side?
For the client side I've written an article on the communication.
If you are on the server side (question seems to go in that direction due to the mention of cookies) then I would suggest using the standard microservice patterns for communication and exchanging state. Of course, using centralized systems such as Redis cache there would help.
In general the different microfrontends should have their own state and be as independent as possible.
Usually what you want to share is not the state / data, but rather the state with an UI representation. The reason is simple: That way you don't have to deal with the representation and edge cases (what if the data is not available?). One framework to show this is Piral.
Hope that helps!
There's no shared state, that'd break the concept of the segregation that's supposed to take place. This pattern is present among all microservices architectures as it's supposed to eliminate single points of failure and other complications in maintaining a bigger store. The common approach is for each "micro frontend" to have its own store (i.e. Redux). The Redux docs have a topic on this.
First, you should avoid having shared states between MicroFrontend (MFE) much as possible. This is a best practice to avoid coupling, reduce bugs, etc..
A lot of times you don't need it, for example, every information/state that came from the server (eg: the "user" information) could be requested individually for each MFE when they need it.
However, in case you really need a shared state there are a few solutions like:
- Implement the pub/sub pattern in the Window object.
There are a few libraries that already provide this.
//MFE 1
import { Observable } from 'windowed-observable';
const observable = new Observable('messages');
observable.publish(input.value); //input.value markup is not present in this example for simplicity
//MFE 2
import { Observable } from 'windowed-observable';
const observable = new Observable('messages');
const handleNewMessage = (newMessage) => {
setMessages((currentMessages) => currentMessages.concat(newMessage)); //custom logic to handle the message
};
observable.subscribe(handleNewMessage);
reference: https://dev.to/luistak/cross-micro-frontends-communication-30m3#windowed-observable
- Dispatch/Capture Custom browser Events
Remember that Custom Events can have 'details' that allow pass information
//MF1
const customEvent = new CustomEvent('message', { detail: input.value });
window.dispatchEvent(customEvent)
//MF2
const handleNewMessage = (event) => {
setMessages((currentMessages) => currentMessages.concat(event.detail));
};
window.addEventListener('message', handleNewMessage);
This approach has the important issue that just works for 'new events dispatched', so you can read the state if you don't capture the event at the moment.
reference: https://dev.to/luistak/cross-micro-frontends-communication-30m3#custom-events
In both implementations, using a good naming convention will help a lot to keep order.
Writing my first Backbone app - came across a predicament wherein i am unable to choose which is the best way to move forward.
Scenario : User clicks an edit button , a new view is loaded . Approach is as below.
renderEditView: function(){
if(my.namespace.view){
my.namespace.view.render();
}else{
my.namespace.view= new editView({model:my.namespace.model});
}
}
Basically, i am assigning my view to a namespaced variable and resuing it as required. Didn't face any problems as such.
But some advocate recreating the View again using new editView({model:xxx}); whenever the edit button is clicked . i Would like to know which one is the better practice and why?
P.S: i am aware of the 'event ghosting' problem in BB apps, and the excellent solution provided by Derick Bailey .But still would love to know the pros and cons between the approaches.
This is indeed an opinion, because either way will work if you (as you mention) take care of cleaning up previous views if you decide to instantiate a new one every time you want to re-render. It's important to avoid duplicating lingering events from every instance that you want to replace by creating a new one.
Personally I have used both strategies and never had problems with them so far.
When re-using a view, I bind the view as a property to the controller object that renders the view, pretty much the same way you do it.
Theoretically, I don't see a reason to re-instantiate a view if it was already created before. It isn't that you really require a new instance, it's just that you want to re-render it.
Sidenote
For re-rendering views, Backbone Marionette offers regions, which are convenience objects that allow you to do things like:
var myView = new MyView();
var region = new Marionette.Region({el: "#container"});
region.show(myView);
In case you would decide to instantiate a new view every time, these regions take care that previously rendered views are properly cleaned up.
I have just started using AutoFixture, and i am getting the basics down (from what i can see there is much more to it) but i am having an issue and i am not 100% sure what the best practice is for stuff like this.
I am testing a controller, and part of the process is the action can return one of two views.
If a category has children - show the category listing view
If a category does not have children show the product listing view
So i am thinking of a few tests for that behavior, but the fixture data returned would be different. One would return a count of 0, the other a greater count then zero, so i would like the fixture to help me with that.
I have been looking around, and maybe i have to create a customisation of some sort, but was hoping the basic API could help me here. I tried this:
var category = _fixture.Build<Category>()
.Do(x => x.SubCategories = _fixture.CreateMany<Category>(3).ToList())
.Create();
_fakeCategoryService
.Setup(x => x.GetById(id))
.Returns(category);
This compiles and tests run (and fail), but the sub categories always has a count of 0, so i am thinking my call to Create Many in the do is all wrong (it kinda looks wrong but i am still unsure what it should be replaced with).
UPDATE: should read the cheat sheet a bit better!
var category = _fixture.Build<Category>()
.With(x => x.SubCategories, _fixture.CreateMany<Category>(3).ToList())
.Create();
This works, if there is a better way please let me know.
Yes, Build is correct.
If you want to customize the creation algorithm for a single Category use Build:
var actual = fixture
.Build<Category>()
.With(x => x.SubCategories,
fixture.CreateMany<Category>().ToList())
.Create();
Assert.NotEmpty(actual.SubCategories);
If you want to customize the creation algorithm for all Category instances use Customize:
fixture.Customize<Category>(c => c
.With(x => x.SubCategories,
fixture.CreateMany<Category>().ToList()));
var actual = fixture.Create<Category>();
Assert.NotEmpty(actual.SubCategories);
was hoping the basic API could help me here
It does help you, if you know how to listen :) AutoFixture was originally build as a tool for Test-Driven Development (TDD), and TDD is all about feedback. In the spirit of GOOS, you should listen to your tests. In this case it's saying the same as the Framework Design Guidelines:
DO NOT provide settable collection properties.
Instead of assigning a list wholesale to a property, consider
making the collection property read-only, and let clients invoke Add, etc.
taking the collection as a constructor parameter instead of mutating property
In the latter case, AutoFixture will automatically provide a populated collection when it invokes the constructor, although in this particular case, since you have a potentially recursive graph, you may need to explicitly handle it.
In the first case, AutoFixture doesn't do anything out of the box, but has an AddManyTo extension method, enabling you to fill a collection in a single statement:
fixture.AddManyTo(category.SubCategories);
You can do this stub with a custom list:
var stub = _fixture.Build<Entity>().With(x=> x.field, config).CreateMany().ToList();
Documentation.
I'm just trying to figure out a probably simple question.
Should views set model data directly or only call model methods that change their own data?
like everything else in software development, "it depends".
if you're using form inputs in your views and you just need to get the data from those inputs in to the models, set the data directly. You can do this any number of ways, including "change" events from the input fields, like this:
MyView = Backbone.View.extend({
events: {
"change #name", "setName"
},
setName: function(e){
var val = $(e.currentTarget).val();
this.model.set({name: val});
}
});
On the other hand, if you're kicking off business logic and other code that happens to set the data in the model (but really only does this as part of the business logic), then you should call a method on the model.
A "state machine" would be a good example of when you would do this. Or, in an image gallery that I wrote, I had some logic around the selection of an image for display. If an image is already selected, don't select it again. I put this logic in a method on my image model:
Image = Backbone.Model.extend({
select: function(){
if (!this.get("selected")){
this.set({selected: true});
}
}
});
As illustrated here, I like to run by the simple rule that if I have zero logic around the call to set, then I set it directly from wherever I am. If there is any logic related to the model, around the set, then I put it in the model.
Either way, when you do want to set data, you should use the set method. Bypassing this and setting the model's attributes directly through model.attributes will prevent a lot of Backbone's code from firing and potentially cause problems for you.
That depends on your programming style. I always set them directly. If the Law of Demeter sounds good to you and you're into object orientation (and possibly with a Java/Microsoft -stack background), then the style would be to create getter/setter methods.
If you on the other hand is in the "Size is the Enemy" camp (I also recommend Jeff Atwood's comments) the you certainly should set model data directly (as I hinted before, I'm in this camp myself).
That being said, Backbone.js models already have getter and setter methods .get and .set. You should not manipulate the .attributes member directly. I'm not as sure you shouldn't read from it, I tend to do that now and then and haven't run problems because of that yet.
I'm fairly new to MVVM, so please excuse me if this problem has a well-known solution.
We are building a bunch of model classes which have some core properties that are loaded up-front, as well as some additional properties which could be lazy-loaded on demand by making a web API call (update: to clarify, it would be a web API call per lazily-loaded property).
Rather than having multiple models, it seems sensible to have a single model with the lazy-loading logic in there. However, it also seems that the lazy-loaded properties should not block when accessed, so that when the View binds to the ViewModel and it binds to the Model, we don't block the UI thread.
As such, I was thinking of a pattern something along the lines of when a lazy property on the Model is accessed it begins an asynchronous fetch and then immediately returns a default value (e.g. null). When the asynchronous fetch is complete, it will raise a PropertyChanged event so that the ViewModel/View can re-bind to the fetched value.
I've tried this out and it seems to work quite nicely, but was wondering:
Are there any pitfalls to this approach that I haven't found out about yet, but will run into as the app increases in complexity?
Is there an existing solution to this problem either built into the framework, or which is widely used as part of a 3rd party framework?
I did something like this in the past and the one thing I kept forgetting about is you can't call your async property through any kind of code behind and expect it to have a value.
So if I lazy-load a list of Customer.Products, I can't reference Customer.Products.Count in the code-behind because the first time it's called the value is NULL or 0 (depending on if I create a blank collection or not)
Other than that, it worked great for the bindings. I was using the Async CTP library for making my async calls, which I found was absolutely wonderful for something like this.
public ObservableCollection<Products> Products
{
get
{
if (_products == null)
LoadProductsAsync();
return _products;
}
set { ... }
}
private async void LoadProductsAsync()
{
Products = await DAL.LoadProducts(CustomerId);
}
Update
I remember another thing I had issues with was data that actually was NULL. If Customer.Products actually returned a NULL value from the server, I needed to know that the async method had run correctly and that the actual value was null so that it didn't re-run the async method.
I also didn't want the async method to get run twice if someone called the Get method a 2nd time before the first async call had completed.
I solved this at the time by having an Is[AsyncPropertyName]Loading/ed property for every async property and setting it to true during the first async call, but I wasn't really happy about having to create an extra property for all async properties.