It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have two simple observables, for example,
val1 = ko.observable("input1");
val2 = ko.observable("input2");
and I want them to act like one, so when one of them changes, the other changes as well.
I know that in common case it's better to use only one observable and bind it to several dom elements. But in my case theese observables live in different templates and objects, so they can't be one variable.
Currently I subscribe one observable to another and vice versa:
val1.subscribe(function(v) {
val2(v);
});
val2.subscribe(function(v) {
val1(v);
});
However when you change the value of one observable, it updates the second, but that causes a ripple effect and updates the first one again, ad infinitum.
How can I set up a two-way binding between two separate observables which sets the value of one when you modify the other without causing an infinite loop?
You can do something like this:
vm1 = {
val1: ko.observable('input1'),
otherProperty: ko.observable('more')
}
vm2 = {
val2: vm.val1,
otherProperty: ko.observable('data')
}
Both vm1.val1 and vm2.val2 resolve to the same observable and therefore the same value.
Sethi's answer will work, but this might be better served with computed observables
Example: http://jsbin.com/exipuq/1/edit
var viewModelA = function(){
this.myVal = ko.observable();
};
var viewModelB = function(otherViewModel){
this.compVal = ko.computed(function(){
return otherViewModel.myVal();
});
};
// create a new viewmodel like normal
var vma = new viewModelA();
// pass the instantiated view model
// into the new one you're creating
var vmb = new viewModelB(vma);
Related
Trying to figure out how to extend entities that I query from breeze.js on a per-view basis in a single page application. Right now breeze is acting as the gate-keeper when it comes to extending (a.k.a materializing) them and I’m wondering what other options are available to allow me to do this. I initially started with knockout’s mapping plugin but found that it refused to handle child collections for some reason so I moved to using breeze’s constructor function and initializer methodology. The problem with this is that you can only define one custom "model" for an entity. I am looking for approaches that would allow a custom "model" of an entity on a per-view basis. I’ve already ruled out multiple managers. Querying meta-data multiple times is a huge unnecessary hit just to get this working.
This diagram visualizes what I’m trying to achieve. Both View 1 and View 2 ultimately query Entity B and both views require their own specific customization of the "model" of Entity B. Since View 1 loads first it’s custom "model" of Entity B "wins" and View 2 doesn’t have the opportunity to customize it. When View 2 eventually runs it’s query, any entities of type B that were already loaded by View 1 will have the custom "model" that View 1 defined which will make View 2 explode during binding. Any entities not already loaded by View 1 will now have View 2's custom "model" which would eventually crash View 1 if it could even get that far down the road. See this post.
My thought was to manually create my own custom "model" for each view that has an Entity observable and I could then iterate over every entity returned from a breeze query and new up this custom "model" and pass in the current item, assigning it to the Entity property. I don't really want to do this because I now have I'll have tons of iteration code everywhere and I'd much rather use knockout's mapping plugin. Pseudo code:
function view1EntityBModel(entity) {
var self = this;
self.Entity = ko.observable(entity);
self.myCustomProperty = ko.observable();
...
}
function view2EntityBModel(entity) {
var self = this;
self.Entity = ko.observable(entity);
self.isExpanded = ko.observable(false);
...
}
I was wondering if there are any other solutions available to achieve this same goal?
Or even better does anyone know how to make the knockout mapping plugin working on child collections?
I think the problem here is that by the time the mapping plugin gets a-hold of the breeze data the Children collection has already been converted into an observable array and the mapping plugin doesn't know that it needs to "call" the Children() property in order to get back a list.
var categoryMapper = {
create: function (options) {
return new categoryModel(options.data);
},
Children: { // this doesn't fire for the children
create: function (options) {
return new categoryModel(options.data);
}
}
}
function categoryModel(data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
}
Guessing that you've moved on by now, but thought I'd offer a recommendation for others in a similar position.
Our solution to a similar situation borrows from the breeze.js TempHire sample solution which implements a client side repository/uow pattern. The solution uses an EntityMananagerProvider to manage multiple EntityManagers. The EntityMananagerProvider makes a single call for metadata, which is then used to create new child EntityManagers - satisfying your concern regarding multiple metadata calls. You can then use custom models/uow/repositories to extend the child manager for specific views.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am new to Objective-C so please do forgive me if this question is silly! But I would like to know what that means.
- (void)setDetailItem:(id)newDetailItem
{
if (_detailItem != newDetailItem) {
_detailItem = newDetailItem;
// Update the view.
[self configureView];
}
}
What these lines do in a detail view controller exactly? Does it mean that a new object, i.e newDetailItem is created and assigned to the already existing detailItem? I don't get the idea of it.
OR
Does it actually mean that this new object is is equal to the details that are present in the "detailItem" already. So, shouldn't it be written as newDetailItem = _detailItem, so that this new object will get the values of _detailItem?
This has kind of confused me a bit :(
Thanks for your time!
The code you are showing is a typical example of a "setter"—a method that assigns a new value to a property; in this case, a property called "detailItem".
This method is generally invoked in one of two ways, either explicitly:
[someObject setDetailItem:someDetailItem];
or via dot notation:
someObject.detailItem = someDetailItem;
_detailItem is an instance variable, or "ivar"; it is an object-local place where the value of the property is actually stored. This code checks to make sure the new value assigned is actually different from the old value, then assigns it and invokes a side effect, presumably updating some UI to display the new value.
Your confusion seems to stem, in part, from the name of the parameter to this method, "newDetailItem". The name here is arbitrary, and doesn't imply that anything is being created. It's new in the sense of being a new value for the property to have, not a new object.
This method is setting the new value newDetailItem to _detailItem.
In this statment if (_detailItem != newDetailItem) it is checking if both are same object or not, by comparing there memory locations.
In _detailItem = newDetailItem; newDetailItem that is passed as id is put to _detailItem.
In case of ARC: The value is retained/copy as in ARC this is not specified.
You are accessing your property directly by _detailItem. You have a property called detailItem in your class.
And then calling a method configureView.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
i am developing the BlackBerry app in which the data comes from the web services.The data contains the phone numbers of the different countries and also there is call functionality in the app.
I have used ActiveRichTextField to display data in labelfield so that phone numbers and email id's can be detected.It also detects the numbers and mail id's but it fails to detect some of the numbers.Do any body know how to detect number such as +618 12345678/79 and sort of the data.Any sort of help is appreciated.
If you are looking to recognise a string in another given string, you want to look at PatternRepository. This is a system managed collection of strings, that is used to add context menus to given strings.
If your string is found on the device, it will show the menu that you define. So you need to subclass ApplicationMenuItem and provide your own run() method.
The following code will set up your device to recognise a regular expression, and create a context menu item for when that pattern is found:
// MyAppMenuItem extends ApplicationMenuItem
MyAppMenuItem appMenuItem = new MyAppMenuItem(0);
ApplicationMenuItem[] applicationMenu = new ApplicationMenuItem[1];
applicationMenu[0] = appMenuItem;
// register the pattern to identify the phone number
PatternRepository.addPattern(
ApplicationDescriptor.currentApplicationDescriptor(),
"*** REGEXP String to recognise phone numbers ***",
PatternRepository.PATTERN_TYPE_REGULAR_EXPRESSION,
applicationMenu);
I found that this does not work in HTML fields (BlackBerry - intercept text in HTML). But it worked in almost all other places across my app, and in other apps, like email. If you only want it to work in your app, you can deregister this pattern when your app exits.
Note that you can add many different patterns to the PatternRepository - one for each style of number or email address that you want to recognise.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why not use an IoC container to resolve dependencies for entities/business objects?
I asked a very similar question in the past. However, I believe this is not a self-duplicate: the (good) answer to my original question was very specific to this domain problem, and does not discuss the problem in general.
Let's take a new example I came accross:
I have a Zone entity, with an associated boundary;
I have a Store entity, which has a location as well as a zone property;
A ZoneRepository can find which Zone contains a specific location.
The zone property of the Store should never be set directly, but instead deducted from the location when this property is assigned. Therefore, it sounds logical to me to do this:
class Store
{
public void setLocation(Point location, ZoneRepository repo)
{
this.location = location;
this.zone = repo.findByLocation(location);
}
}
Are there drawbacks, caveats to this approach? If so, can you suggest realistic alternatives?
What is the relationship between Zone and Location? Zone must have a Location property, correct? Or otherwise you wouldn't be able to search zone by location. Could this be a bi-directional relationship? What I'm getting at, is why can't you do this?
class Store
{
public function setLocation(Point $location)
{
$this->location = $location;
$this->zone = $location->zone;
}
}
alternatively, you cold use the repository in the layer above, and then just pass in what you need:
class Store
{
public function setLocation(Point $location, Zone $zone)
{
$this->location = $location;
$this->zone = $zone;
}
}
Generally, I would not inject the repository in unless absolutely necessary, and in this situation it is not. Even then, I would not pass it into the method, I would pass it in using an IOC container.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
What is the need/purpose of converting an image to a byte array?
Why do we need to do this?
What's the purpose of converting an Image to a byte array?
Saving an image to disk
Serializing the image to send to a web service
Saving the image to a database
Serializing the image for processing
...are just a few that I can think of off the top of my head.
I think the most common use would be saving an image in a database (BINARY(MAX) data type).
Most common is to persist the image in the database as a blob (binary large object) but it could also be used in web services where you could take in a byte array as a method argument and then convert that to an image for whatever reason.
the only time i've ever needed to do this was to compare two images pixel-by-pixel to see if they were identical (as part of an automated test suite). converting to bytes and pinning the memory allowed me to use an unsafe block in C# to do a direct pointer-based comparison, which was orders of magnitude faster than GetPixel.
Recently I wrote a code to get hash from image, here is how:
private ImageConverter c = new ImageConverter();
private byte[] getBitmapHash(Bitmap hc) {
return md5.ComputeHash(c.ConvertTo(hc, typeof(byte[])) as byte[]);
}
Here is this in context. Serializing image or adding it to database in raw byte format (without mime type) is not something that seems to be sensible, but you can do that. Image processing and cryptography are most likely of places where this is useful.
To further generalize what Brad said: Serialization and (probably) a basis for object comparison.
Also is helpful if you have a image in memory and want to send it to someone via a protocol (HTTP for example). A perfect example would be the method "AddBytesForUpload" in the Chilkat HTTPRequest clas [http://www.chilkatsoft.com/refdoc/vbnetHttpRequestRef.html].
Why would you ever need to do this you may ask... Well lets assume we have a directory of images we want to auto upload to imageshack, but do some mods before hand like put our domain name at the bottom right. With this, u load the image in memory, do the mods with it that u need, then simply attach that stream to the HTTPRequest object. Without the array u would need to then same to a file before uploading, which in turn will create either a new file u then need to delete after, or over write the original, which is not always ideal.
public byte[] imageToByteArray(System.Drawing.Image image)
{
MemoryStream ms = new MemoryStream();
image.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
If it is a image file use File.ReadAllBytes().