-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
1f34162
commit 615b152
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
# Define the S3 class constructor | ||
MyS3Class <- function(value) { | ||
structure(list(value = value), class = "MyS3Class") | ||
} | ||
|
||
# Define print method for MyS3Class | ||
print.MyS3Class <- function(x, ...) { | ||
cat("MyS3Class object with value:", x$value, "\n") | ||
} | ||
|
||
# Create an active binding function | ||
create_active_binding <- function(name, initial_value) { | ||
value <- initial_value | ||
|
||
# Remove existing binding if it exists | ||
if (exists(name, envir = .GlobalEnv)) { | ||
rm(list = name, envir = .GlobalEnv) | ||
} | ||
|
||
makeActiveBinding( | ||
name, | ||
function(v) { | ||
if (missing(v)) { | ||
return(value) | ||
} else { | ||
cat("hello\n") | ||
value <<- MyS3Class(v) | ||
} | ||
}, | ||
.GlobalEnv | ||
) | ||
} | ||
|
||
# Create an object of MyS3Class | ||
obj <- MyS3Class(10) | ||
|
||
# Create an active binding for the object | ||
create_active_binding("obj", obj) | ||
|
||
# Access the value | ||
print(obj) # Should print 10 | ||
|
||
# Assign a new value and trigger the custom logic | ||
obj <- 29 # Should print "hello" | ||
print(obj) # Should print 29 |